简体   繁体   English

如何在java中声明可以存储超类和子类对象的数组?

[英]How to declare array that can store superclass and subclass object in java?

I am trying to figure out how to create an array that can store super class and subclass objects.我想弄清楚如何创建一个可以存储超类和子类对象的数组。

   Book[] books = new Book[10]

Do i have to use the keyword super or sub ?我必须使用关键字 super 或 sub 吗? please clear my doubt.请清除我的疑问。

Thank you谢谢

Let's assume Book is your super class and then your sub class is ->让我们假设 Book 是您的超类,然后您的子类是 ->

Class SuspenseBook extends Book {
//code...
}

Now your array,现在你的阵列,

Book[] books = new Book[10]

can store objects of Book as well as SuspenseBook objects.可以存储 Book 对象以及 SuspenseBook 对象。

Let me know if this helps.如果这有帮助,请告诉我。

Yes you can store Subclass object inside a super class array of objects.是的,您可以将 Subclass 对象存储在超类对象数组中。 Lets say you have this piece of code:假设你有这段代码:

class Animal {
    void saySomething() {System.out.print(" Hummmmm!");}
}

class Cow extends Animal {
    protected void saySomething() {System.out.print(" oMooo!");}
}
public class test {
    public static void main(String [] args) {
        System.out.print(" MooYa!");
        Animal [] animals = {new Animal(), new Cow()};
        for( Animal a : animals) {
            a.saySomething();
        }
    }
}

This particular piece of code has Animal[] animals = { new Animal(), new Cow()} on line number 11. This code will create an array of the superclass type (ie Animal ) and will initialize two objects - one of the superclass and one of the subclass to be stored in the array.这段特殊的代码在第 11 行有Animal[] animals = { new Animal(), new Cow()} 。这段代码将创建一个超类类型(即Animal )的数组,并将初始化两个对象 - 其中一个是超类和要存储在数组中的子类之一。 Now since the subclass Cow inherits the superclass Animal therefore adding the Cow class object to the superclass array could be re-written as : Animal animals = new Cow();现在,由于子类Cow继承了超类Animal因此将Cow类对象添加到超类数组可以重写为: Animal animals = new Cow(); This is polymorphism where a superclass reference variable can used to store the address of a subclass object.这是多态性,其中超类引用变量可用于存储子类对象的地址。 In short the superclass can take forms of the subclass( book definition).简而言之,超类可以采用子类(书籍定义)的形式。

**Thus to answer you question you can store subclass object inside a superclass array. **因此要回答您的问题,您可以将子类对象存储在超类数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM