this Key words and super What do the keywords stand for ? And their respective scenarios and roles .
this: References to the current object , It exists inside the ordinary member method
effect :
- Used inside the normal member method of a class
- Use format as
this. Member variables
,this. Member method
this
Reference representing the current object
super: Identification of the parent storage space ( Reference to the current parent object )
Usage scenarios and differences
-
Member variables :
- this. Variable Member variables in this class
- super. Variable Member variables in the parent class
class Animal { String name; public Animal() { } public Animal(String name) { this.name = name; } public void showName() { } } class Dog extends Animal { public Dog() { } public Dog(String name) { super(name); } public void showName() { System.out.println(super.name); } }
-
Construction method :
- this(…) The construction method in this class
- super(…) The construction method in the parent class
class Animal { String name; int age; public Animal(String name) { this(name,1); } public Animal(String name,int age) { this.name = name; this.age=age; } public void showName() { } } class Dog extends Animal { public Dog(String name) { super(name); } public Dog(String name,int age) { super(name,age); } public void showName() { System.out.println(super.name); System.out.println(this.age); } }
-
Member method :
- this. Method name () Member methods in this class
- super. Method name () Member methods in the parent class
class Animal { String name; int age; public Animal(String name) { this(name,1); } public Animal(String name,int age) { this.name = name; this.age=age; } public void showName() { System.out.println(" Parent class showName() Method "); } } class Dog extends Animal { public Dog(String name) { super(name); } public Dog(String name,int age) { super(name,age); } public void showName() { super.showName(); System.out.println(super.name); this.showAge(); } public void showAge() { System.out.println(this.age); } }
this and super Description of the difference between
- When a member variable and a local variable have the same name , have access to
this
To distinguish between . - this Can be used in constructors , Call other constructors ( It can only be defined in the first line , Initialization must be executed ).
super
can Call the parent class directly 、 Method 、 Construction method . But when you call the constructor , You can’t use both at the same time . super()
Call parent constructor from subclass ,this() Call other methods in the same class .this
andsuper
Cannot appear in a constructor at the same time .super()
andthis()
Must be placed in the first line of the construction method .this
andsuper
Are all objects , So no more static Use in the environment .