1. There are three uses of the super keyword:
1. In the member method of the subclass, access the member variables of the parent class (with or without the same name).
public class Fu3 { int num = 10; }
public class Zi3 extends Fu3{ int num = 20; public void method(){ System.out.println(num); // 20 principle of proximity System.out.println(super.num); // 10 member variables of the parent class } }
2. In the member method of the subclass, access the member method of the parent class (with or without the same name).
public class Fu3 { int num = 10; public void method(){ System.out.println("The member method of the parent class"); } }
public void method2(){ method(); // nearest super.method(); // parent class }
3. In the construction method of the subclass, visit the construction method of the parent class.
Summary: The super keyword is used to access the content of the parent class in the subclass, and the this keyword is in the content of this class.
There are three usages of this keyword:
1. In the member method of this class, access the member variables of this class (with or without the same name).
int num = 10; public void method(){ int num = 20; System.out.println(num); // 20 local variables System.out.println(this.num); // 10 member variables of this class }
2. In the member methods of this class, access another member method of this class.
public void methodA(){ System.out.println("AAA"); } public void methodB(){ methodA(); // can be called directly this.methodA(); System.out.println("BBB"); }
3. In the construction method of this class, visit another construction method of this class.
public Demo04Constructor() { // super(); // This line is no longer given away this(123); // This is the parameterless construction method of this class, call the parameterized construction of this class System.out.println("No parameter construction method"); } public Demo04Constructor(int n) { System.out.println("Parameter construction method"); }
note:
A. Note that in the third English and French, this (...) call must be the first and only statement in the constructor.
B. Super and this two construction calls cannot be used at the same time, because they are required to be the only first one.