2017-02-16 127 views
-2

子類如何更改父類實例變量的值。我在子類中使用super.variable名稱嘗試過它,但是當我打印父類時。變量名我可以看到變化沒有反映在父變量中子類可以如何更改父類實例變量的值

+1

你能顯示代碼嗎? – Jeet

+0

我想你應該使用Java書籍而不是stackoverflow ... – Jay

+0

孩子已經從其父母繼承(公共和受保護的)變量,因此您可以通過使用this.variable訪問和更改它。 – Raptor

回答

1

更新父變量與parent.variable是OOP的錯誤思想。當你擴展父類時,想像你的子類與父類一樣,它們不再分離,所以從現在開始想像變量是孩子的。但是隻是切片差異是publicprivate定義它設置每個類的項目的可見性。因此,在下面的示例中,我只爲父級定義了一個私有變量,以便孩子無法看到它,但孩子能夠通過公共getter setter更新變量。這是因爲我們使用getter和setter來提供封裝,因爲它只與Parent類有關。請調查代碼以瞭解更多:

class Main { 

    public static class Parent { 
     private int variable; 

     public int getVariable() { 
      return variable; 
     } 

     public void setVariable(int variable) { 
      this.variable = variable; 
     } 
    } 

    public static class Child extends Parent { 

     private int childVadiable; 

     public Child() { 

     } 

     public int getChildVadiable() { 
      return childVadiable; 
     } 

     public void setChildVadiable(int childVadiable) { 
      this.childVadiable = childVadiable; 
     } 

     public void updateParentVariable(int value) { 
      this.setVariable(value); 
     } 

    } 

    public static void main (String[] args) { 

     Child child = new Child(); 
     child.updateParentVariable(5); 
     System.out.println(child.getVariable()); 
     //Result it '5' 
    } 

} 
相關問題