英文:
Can I create an array of a parent class that contains its subclasses and then apply subclass methods to the array?
问题
In java, can I create an array of a parent class that contains its subclasses. Then after that, can I apply the methods found in the subclass to the object in the array.
例如,
Animal[] c =new Animal[6];
c[0] = new Dog(new Animal());
c[0].setBreedOfDog("Pug")
在这个例子中,我创建了一个使用Animal的父类数组,然后将子类Dog放入其中。但是当我尝试使用Dog类中的setter方法时,我会收到一个错误。我不能用指针这样做吗? 有人能告诉我为什么吗?谢谢。
英文:
In java, can I create an array of a parent class that contains its subclasses. Then after that, can I apply the methods found in the subclass to the object in the array.
For example,
Animal[] c =new Animal[6];
c[0] = new Dog(new Animal());
c[0].setBreedOfDog("Pug")
In this, I create an parent array using Animal, and then put in the subclass Dog into it. But when I try to use a setter in the Dog class, I get an error. Can't I do this with pointers? Can anyone tell me why this is. Thank you.
答案1
得分: 1
你需要将数组项转换为表示类的 Dog
。
Animal[] c = new Animal[6];
c[0] = new Dog();
((Dog) c[0]).setBreedOfDog("Pug");
英文:
You'll need to cast your array item to the representing class, Dog
.
Animal[] c = new Animal[6];
c[0] = new Dog();
((Dog) c[0]).setBreedOfDog("Pug");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论