你可以创建一个包含其子类的父类数组,然后对数组应用子类方法吗?

huangapple go评论69阅读模式
英文:

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");

huangapple
  • 本文由 发表于 2023年5月22日 21:59:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定