Java中Super()与this()
super指父类,this指当前对象
super()与this()都必须在构造函数第一行,一个构造函数不能同时有super()和this(),子类的构造函数都隐式地调用super(),super()与this()都不能在static环境中使用(父类的static方法不能被继承),从本质上讲,this是一个指向本对象的指针,super是一个java关键字。
举例说明:
父类:
public class Father {
public Father(){
System.out.println("Father");
}
public Father(String str) {
System.out.println(str+" in Father");
}
}
子类:
public class Son extends Father {
public Son(){
//隐式调用super()
System.out.println("son");
}
public Son(String str){
System.out.println(str+" in Son");
}
public static void main(String[] args){
Son son = new Son();
}
}
输出结果是:
Father
Son
父类:
public class Father {
public Father(){
System.out.println("Father");
}
public Father(String str) {
System.out.println(str+" in Father");
}
}
子类:
public class Son extends Father {
public Son(){
this("Test");
//这里由于this的存在,不会再隐式调用super()
System.out.println("son");
}
public Son(String str){
//仍然隐式调用super(),而不是隐式调用super(str)
System.out.println(str+" in Son");
}
public static void main(String[] args){
Son son = new Son();
}
}
输出结果是:
Father
Test in Son
son
父类:
public class Father {
public Father(){
System.out.println("Father");
}
public Father(String str) {
System.out.println(str+" in Father");
}
}
子类:
public class Son extends Father {
public Son(){
this("Test");
//这里由于this的存在,不会再隐式调用super()
System.out.println("son");
}
public Son(String str){
super(str);
//显示调用super(str),而不再隐式调用super()
System.out.println(str+" in Son");
}
public static void main(String[] args){
Son son = new Son();
}
}
输出结果是:
Test in Father
Test in Son
son
父类中如果存在成员函数,可在子类中使用super.function()的形式调用父类的成员函数function().