码迷,mamicode.com
首页 > 其他好文 > 详细

子类继承父类时,子类与父类有同名变量,当使用子类对象调用父类方法使用同名变量,这个变量是子类的,还是父类的? (改)

时间:2017-05-10 19:53:00      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:int   ++   minus   one   code   val   return   logs   turn   

 1 public class Test4 {
 2     public static void main(String[] args){
 3         Son son = new Son();
 4         son.minusOne();
 5         System.out.println(son.testValue);
 6         System.out.println(son.getSuperTestValue());
 7         son.plusOne();
 8         System.out.println(son.testValue);
 9         System.out.println(son.getSuperTestValue());
10     }
11 }
12 class Father{
13     int testValue = 100;
14     public void minusOne(){
15         this.testValue--;
16     }
17 }
18 class Son extends Father{
19     int testValue = 0;
20     public void plusOne(){
21         testValue++;
22     }
23     public int getSuperTestValue(){
24         return super.testValue;
25     }
26 }

结果为  0 99 1 99

  所以,当使用子类对象调用方法使用同名变量,是按照方法来判断使用哪一个变量,调用父类的方法,使用的是父类中的变量   ,  调用子类的方法,使用的是子类中的变量

 

子类继承父类时,子类与父类有同名变量,当使用子类对象调用父类方法使用同名变量,这个变量是子类的,还是父类的? (改)

标签:int   ++   minus   one   code   val   return   logs   turn   

原文地址:http://www.cnblogs.com/kirikayakazuto/p/6837528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!