Java中的super和this
this关键字
- 调用当前对象的属性或方法
public class Father {
public String name;
public void show(){
System.out.println(this.name);
}
public void toShow(){
this.show();
}
}
public static void main(String[] args) {
Father father = new Father();
father.name = "父类"
father.show();
father.toShow();
}
- 调用构造方法
public class Father {
public Father(){
System.out.println("无参构造");
}
public void show(){
this();
}
}
public static void main(String[] args) {
Father father = new Father();
father.show();
}
super关键字
public class Father {
public String name;
public Father(){
System.out.println("父类的无参构造");
}
public void show(){
System.out.println(name);
}
}
- 访问父类的属性或方法
public class Son extends Father {
public void myFather(){
super.name = "Father"
super.Show();
}
}
public static void main(String[] args) {
Son son = new Father();
son.myFather();
}
- 调用父类的构造方法
public class Son extends Father {
public void myFather(){
super();
}
}
public static void main(String[] args) {
Son son = new Father();
son.myFather();
}