super and this
super
指向父类的一个指针, 引用父类中的属性,方法或者构造函数
public class Father {
String name ;
Father(String myName){
name = myName;
System.out.println("name from father: "+name);
}
protected void outPut(){
System.out.println("use super to get father's method");
}
}
public class SonClass extends Father{
SonClass(){
super("sandy");//调用父类的构造函数Father(String myName)
super.outPut();//调用父类的方法
System.out.println(super.name);//调用父类的属性
}
public static void main(String [] args){
SonClass sClass = new SonClass();
}
}
this:指向本实例的一个指针,调用本实例中的构造函数或者属性。应该为构造函数中的第一条语句
public class SonClass {
String name;
SonClass(){
//super("sandy");
// super.outPut();
System.out.println("test");
}
SonClass(String name){
this();//调用本类的构造函数SonClass();
this.name = name;//给本类的属性name赋值
System.out.println(name);
}
public static void main(String [] args){
SonClass sClass = new SonClass("wendy");
}
}