1.子类继承父类。在创建子类时,会先调用父类的构造方法。
2.在子类中调用父类的方法,父类中的this关键字,是子类对象的实例。
示例程序如下。
Father.java
public class Father {
protected void oncreate() {
//this-->child
f = new ObjectDemo(this);
System.out.println("f:" + f.toString());
System.out.println("父类中的this对象:" + this.toString());//在child中调用,就是child对象
}
public Father(){
System.out.println("Father()");
}
public Father(String str){
System.out.println("Father(String str)");
}
}
Child.java
public class Child extends Father{
@Override
protected void oncreate(){
//this-->child
super.oncreate();
}
public Child(){
/*
* 没有指定super,子类会先调用父类默认的空构造方法
* 如果指定super,子类会调用指定的构造方法
*/
super("father");
System.out.println("Child()");
}
}