今天,在群里有人问(估计是新手)。答案,不一定。只有当子类重写了父类的方法时,如果需要用到父类的方法时,才要用super,表明这个方法时父类的方法不是子类的方法。不理解?上代码:
Father类
public class Father {
public String str = "父类变量";
public String strOnly = "父类变量,子类没有同名变量";
public void printf(String str){
System.out.println(str+"这是父类的方法");
}
public void printfOnly(String str){
System.out.println("这是父类的方法,子类没有重写的方法====>"+str);
}
}
Son类:
public class Son extends Father{
public String str = "子类变量";
public void printf(String str){
System.out.println(str+"这是子类的方法");
}
public void test() {
printf("什么都不使用=======>");
this.printf("使用this=======>");
super.printf("使用super=======>");
printfOnly("子类没重写,就会调用父类的方法");
System.out.println("str is ===========>"+str);
System.out.println("super.str is ===========>"+super.str);
System.out.println("子类没有同名变量,就会去找父类的变量 ===========>"+strOnly);
}
public static void main(String[] args) {
Son son = new Son();
son.test();
}
}
运行结果:
什么都不使用=======>这是子类的方法
使用this=======>这是子类的方法
使用super=======>这是父类的方法
这是父类的方法,子类没有重写的方法====>子类没重写,就会调用父类的方法
str is ===========>子类变量
super.str is ===========>父类变量
子类没有同名变量,就会去找父类的变量 ===========>父类变量,子类没有同名变量
子类重写printf方法,如果需要调用父类的方法就要加super,否则,默认调用子类的方法。对于变量也是一样。