使用父类方法一定要用super吗(写给新人)
来源:互联网 发布:java后端工作累不累 编辑:程序博客网 时间:2024/05/20 02:23
今天,在群里有人问(估计是新手)。答案,不一定。只有当子类重写了父类的方法时,如果需要用到父类的方法时,才要用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,否则,默认调用子类的方法。对于变量也是一样。
阅读全文