亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

很難讓我的子類準確地覆蓋我的父類

很難讓我的子類準確地覆蓋我的父類

PIPIONE 2023-11-01 21:05:34
我對編碼并不陌生,但對多態性/繼承等不熟悉。我對靜態/動態綁定感到困惑,特別是當我將不同的子類放在一個數組中時會發生什么。我正在研究一些非常簡單的動物課程,只是想學習基礎知識。我也嘗試將它們定義為獅虎,但是當我嘗試打印動物大小數組時,它們的大小都是-1。我現在的方式給了 p0 正確的大小,但不是 p1 。   public abstract class Animal {    public int size = -1;      }   public class Tiger extends Animal {   }   public class Liger extends Animal {     public int size = 121;   }   public static void main(final String[] args) {    Animal[] animal = new Animal[10];    Animal p0 = new Liger();    p0.size = 11;    animals[0] = p0;    Animal p1 = new Liger();    animals[1] = p1;  }當我將獅虎定義為動物時,p1 的大小為 -1,而不是我想要的 121。我確信問題在于我將其稱為動物而不是獅虎,但我不確定修復它的正確語法是什么。我希望他們能夠與老虎并列。
查看完整描述

2 回答

?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

public abstract class Animal {

    private int size;


    public Animal() {

        size = -1;

    }


    public Animal(int size) {

        this.size = size;

    }


    public void setSize( int size ) {

        this.size = size;

    }


    public int getSize() {

        return size;

    }


    public static void main(final String[] args) {


      Animal[] animals  = new Animal[2];

      animals[0] = new Liger(20);

      animals[1] = new Liger();


      for(int i = 0; i < animals.length; ++i) {

          System.out.println("Size : " + animals[i].getSize());

      }   

    }

}


public class Tiger extends Animal {

      public Tiger() {

         super();    

      }


      public Tiger(int size) {

         super(size);

      }

}


public class Liger extends Animal {

      public Liger() {

         super();    

      }


      public Liger(int size) {

         super(size);

      }  

}

這只是一個基本準則,僅供參考。這里的要點是可以在后續子類中覆蓋行為。Java教程


查看完整回答
反對 回復 2023-11-01
?
HUH函數

TA貢獻1836條經驗 獲得超4個贊

請問你的行中的fs是什么


Animal p1 = fs.new Liger();

順便說一句,看看這段代碼并告訴我它是否符合您的要求。


public static void main(final String[] args) {


    Animal[] animals = new Animal[10];


    Animal p0 = new Liger();

    p0.size = 11;

    animals[0] = p0;


    Animal p1 = new Liger();

    animals[1] = p1;


    System.out.println("p0.size "+ p0.size); // call as a superclass instance

    System.out.println("real p0.size "+ ((p0 instanceof Liger) ? ((Liger)p0).size : ((Tiger)p0).size) ); // cast to call the effective instance of the subclass

    System.out.println("p1.size "+ p1.size); // call as a superclass instance

    System.out.println("real p1.size "+ ((p1 instanceof Liger) ? ((Liger)p1).size : ((Tiger)p1).size) ); // cast to call the effective instance of the subclass



}


查看完整回答
反對 回復 2023-11-01
  • 2 回答
  • 0 關注
  • 212 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號