【问题标题】:Trying to understand this polymorphism exercise试图理解这个多态性练习
【发布时间】:2015-06-24 22:00:27
【问题描述】:

在书中,他们尝试使用数组对象,使用多态性来创建自己的 arrayList 类。

我了解代码在做什么,但它不允许它编译,因为它们不是狗或猫类。 我将它们分别放在单独的文件中。

错误:动物无法解析为类型

public class MyAnimalList {
    private Animal[] animals = new Animal[5];
    private int nextIndex = 0;

    public void add(Animal a ) {
        if (nextIndex < animals.length) {
            animals[nextIndex] = a;
            System.out.println("Animal added at " + nextIndex);
            nextIndex++;
        }
    }

}

//next snippet

public class AnimalTestDrive{
    public static void main (String[]args) {
        MyAnimalList list = new MyAnimalList():
        Dog a = new Dog();
        Cat c = new Cat();
        list.add(a);
        list.add(c);
    }
}

【问题讨论】:

  • 创建动物类后,我不再收到错误“动物无法解析为类型”,现在我正在尝试弄清楚如何制作动物的类型,接受“添加"方法。
  • 本书示例中没有包含动物或狗或猫的类,但假设狗和猫显然是动物,应该从动物类扩展。感谢您的帮助,只是想弄清楚这一切是如何结合在一起的

标签: java


【解决方案1】:

好的,所以多态性的整个概念是对象可以分为更通用的对象。

例如:狗是动物,猫是动物,动物是生物

因此,多态允许您为一个类(动物)定义一堆通用特征(即字段和方法),以便归类在该类(猫、狗等)下的所有其他类都可以扩展这些特征。

现在你的代码不工作的原因是因为你没有定义狗或猫类,为了做到这一点,你需要首先创建一个具有某些属性的类动物:

public class Animal{
    //some fields

    //constructor

    //methods
}

然后创建另外两个类 Dog 和 Cat 来扩展它(extend 是一个关键词,表示这个对象属于的类别)

所以你会创建:

public class Dog extends Animal{
    //some fields

    //constructor

    //methods
}

public class Cat extends Animal{
    //some fields

    //constructor

    //methods
}

【讨论】:

    【解决方案2】:

    您是现代 IDE(例如 Eclipse)吗?还是从命令行执行?

    ** 如果您不使用 IDE,我强烈建议您从一开始就这样做。它将帮助您走得更顺畅、更快。 **

    如果您使用命令行工具编写程序,请仔细查看oracle documentation

    特别是-cp参数

    您必须提供一个文件夹,java 可以在其中找到已编译的类文件,这就是 -cp 的用途。对于您的情况,java 似乎无法找到其他 .class 文件(动物或狗等)。

    多态概念

    狗、鱼和鸟都是动物。所以它们都继承了一些基本概念。例如,他们都在移动。然而,一条狗跑,一条鱼游,一只鸟飞。让我向您展示它是如何在 OO 中完成的:

    abstract class Animal{
     move();
    }
    
    
    class Dog extends Animal{
       private run(){
         ...
         // implementation
         ...
       }
    
       public move(){
          run();
       }
    }
    
    
    class Bird extends Animal{
       private fly(){
         ...
         implementation
       }
    
       public move(){
          fly();
       }
    }
    
    
    class Fish extends Animal{
       private swim(){
         ...
         implementation
       }
    
       public move(){
          swim();
       }
    }
    
    
    I hope it makes sense =]
    

    PS:以上代码是伪代码,不是Java

    【讨论】:

      【解决方案3】:

      1) 必须创建一个公共动物类

      2) 必须创建 dog 和 cat 子类,都必须扩展 animal。从动物扩展将允许狗和猫都接受“添加”方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-16
        • 2021-03-10
        • 1970-01-01
        相关资源
        最近更新 更多