子類繼承父類時,子類與父類有同名變量,當使用子類對象調用父類方法使用同名變量,這個變量是子類的,還是父類的? (改)


 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

  所以,當使用子類對象調用方法使用同名變量,是按照方法來判斷使用哪一個變量,調用父類的方法,使用的是父類中的變量   ,  調用子類的方法,使用的是子類中的變量

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM