This points to the current object, used to access its methods and properties, and is often used in constructors; super points to the parent class, used to call parent class methods or access its properties, and is often used to override parent class methods or access Properties that are not overridden.
The difference between this and super in Java
This and super are both keywords in Java , which are used to access methods and properties of a class.
this
this
keyword is used to refer to the current object. super
super
keyword is used to refer to the parent class. Main differences
Features | this | super |
---|---|---|
Purpose | Reference the current object | Reference the parent class |
Scope | Current class | Parent class |
Syntax | this.propertyName/methodName | super.propertyName/methodName |
Initialization | Initialize the object state in the constructor | Access the constructor of the parent class |
Override Method | cannot be used to override parent class methods | can be used to override parent class methods |
Example
<code class="java">class Parent { public void printName() { System.out.println("Parent"); } } class Child extends Parent { @Override public void printName() { System.out.println("Child"); } public void callSuper() { super.printName(); // 调用父类的方法 } }</code>
Output:
<code>Child Parent</code>
The above is the detailed content of The difference between this and super in java. For more information, please follow other related articles on the PHP Chinese website!