为了账号安全,请及时绑定邮箱和手机立即绑定

很难让我的子类准确地覆盖我的父类

很难让我的子类准确地覆盖我的父类

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 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信