你需要提前知道的知识
双亲委派机制
本篇文章已经默认你已经理解了类加载机制
尤其是双亲委派机制
如果你还不知道可以点一下面的连接看一下
隐式调用
我们已经知道根据双亲委派机制我们在调用一个类的时候会优先加载它的父类 加载它的父类这个过程就被称做隐式调用
显式调用
使用this,super这些关键字就叫做显示调用
本篇文章要说的知识点
this关键字在构造器中所代表的是当前正在初始化的Java对象
我们来举一个例子
父类
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;
}
}
在父类的构造器中我们使用了this这个关键字并且写了供子类重载的一个方法
getDec()
子类
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));
}
}
结果
为什么我们输入的有东西但是我们输出的都是空?
我们这里不妨画个构造器里面的图来让我们理解一下
因为类加载器先加载了父类 父类的构造器里面调用了 this.dec=getDec();
但是我们现在是再son()这个类里面所以this调用的就是son的getDec()
,getDec()方法执行就return “the son name=”+name+" weight="+weight;了
根据这个例子我们可以看到在极端情况下父类是可以调用子类的方法
我们再把代码给修改一下调用子类的方法