Article directory
What you need to know ahead of time
Parental delegation mechanism
This article has assumed that you already understand the class loading mechanism
, especially the parent delegation mechanism.
If you don't know it yet, you can click the link below to take a look.
Article on class loading mechanism
Implicit call
We already know that according to the parent delegation mechanism, when we call a class, we will load its parent class first. This process of loading its parent class is called implicit calling.
explicit call
Using the keywords of this and super is called an explicit call
Knowledge points to be said in this article
The this keyword in the constructor represents the Java object that is currently being initialized
Let's take an example
father
package java_this;
public class father {
private String dec;
public father() {
this.dec=getDec();
}
public String getDec(){
return "this is father";
}
public String toString(){
return dec;
}
}
In the constructor of the parent class, we use the this keyword and write a method
getDec() that is overloaded by the child class
Subclass
package java_this;
public class son extends father{
private String name;
private double weight;
public son(String name,double weight){
this.name=name;
this.weight=weight;
}
@Override
//我们重写了这个方法 父类的方法只return了一个"this is father"
public String getDec(){
return "the son name="+name+" weight="+weight;
}
public static void main(String[] args) {
System.out.println(new son("wxt",80));
}
}
result
Why does our input have something but our output is empty?
We might as well draw a picture in the constructor to let us understand
because the class loader first loads the parent class and the parent class constructor calls this.dec=getDec();
but we are now son() this class Inside, this calls the son's getDec()
, and the getDec() method returns "the son name="+name+" weight="+weight; when executed.
According to this example, we can see that in extreme cases, the parent class can call the method of the subclass
Let's modify the code to call the method of the subclass