子类调用父类方法时用super和this的区别所在

基础不扎实的朋友应该会有一个疑问,当super和this都可以用的时候,到底我们是用super调用父类方法还是用this呢?

这里其实是分两种情况的:

当子类重写了父类的方法时,如果需要用到父类的方法时,才要用super,表明这个方法时父类的方法不是子类的方法。上代码:

Father类

[java]  view plain  copy
  1. public class Father {  
  2.       
  3.     public String str = "父类变量";  
  4.       
  5.     public String strOnly = "父类变量,子类没有同名变量";  
  6.       
  7.     public void printf(String str){  
  8.         System.out.println(str+"这是父类的方法");  
  9.     }  
  10.       
  11.     public void printfOnly(String str){  
  12.         System.out.println("这是父类的方法,子类没有重写的方法====>"+str);  
  13.     }  
  14. }  
Son类:

[java]  view plain  copy
  1. public class Son extends Father{  
  2.   
  3.     public String str = "子类变量";  
  4.       
  5.       
  6.     public void printf(String str){  
  7.           
  8.         System.out.println(str+"这是子类的方法");  
  9.     }  
  10.       
  11.     public void test() {  
  12.         printf("什么都不使用=======>");  
  13.         this.printf("使用this=======>");  
  14.         super.printf("使用super=======>");  
  15.         printfOnly("子类没重写,就会调用父类的方法");  
  16.           
  17.         System.out.println("str is ===========>"+str);  
  18.         System.out.println("super.str is ===========>"+super.str);  
  19.         System.out.println("子类没有同名变量,就会去找父类的变量 ===========>"+strOnly);  
  20.     }  
  21.       
  22.     public static void main(String[] args) {  
  23.          Son son = new Son();  
  24.          son.test();       
  25.     }  
  26.       
  27. }  
运行结果:

[java]  view plain  copy
  1. 什么都不使用=======>这是子类的方法  
  2. 使用this=======>这是子类的方法  
  3. 使用super=======>这是父类的方法  
  4. 这是父类的方法,子类没有重写的方法====>子类没重写,就会调用父类的方法  
  5. str is ===========>子类变量  
  6. super.str is ===========>父类变量  
  7. 子类没有同名变量,就会去找父类的变量 ===========>父类变量,子类没有同名变量  


子类重写printf方法,如果需要调用父类的方法就要加super,否则,默认调用子类的方法。对于变量也是一样。

转载自:https://blog.csdn.net/doye_chen/article/details/78887382
原创文章 25 获赞 5 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41450959/article/details/80668749