问题描述
我目前正在学习 Java,但确实遇到了一些困难.所以我有一个带有子类CD"、游戏"和DVD"的磁盘"类.我有一个数据库"类,它在数组列表中创建磁盘、游戏和 cd 的新实例.数组列表初始化如下:
I am currently learning Java and I'm really struggling with something. So I have a Class "Disk" with the subclasses "CD","Game", and "DVD". I have a "database" class which creates new instances of disk,game and cd in an array list. The array list is initialised like so:
private ArrayList<Disk> disks = new ArrayList();
然后我将一个 Game 实例添加到数组中:
I then add an instance of Game to the array:
disks.add(new Game(1999,"SuperGame!",900,"xbox","ea"));
我正在尝试使用以下代码访问游戏子类中的getConsole"方法:
I'm trying to access a method, "getConsole" in the Game subclass using the following code:
Disk currentDisk = disks.get(3);
currentDisk.getConsole();
它说 getConsole 方法不存在.我可以看到问题在于它只访问 Disk 类的方法和字段,但是我如何才能使它可以访问它定义为的子类的方法.感谢您的时间:)
It says the getConsole method doesn't exist. I can see the problem is that it's only accessing the Disk class' methods and fields but how can I make it so it can access the methods of the subclass that it is defined as. Thanks for your time :)
推荐答案
由于 getConsole()
仅在 Game
子类上可用,您需要告诉 Java 您知道您正在查看游戏
,并明确地进行转换:
Since getConsole()
is available only on the Game
subclass, you need to tell Java that you know you're looking at a Game
, and cast explicitly:
Disk currentDisk = disks.get(3);
if (currentDisk instanceof Game) {
((Game)currentDisk).getConsole();
}
这不是在 Java 中做事的好方法,因为您正在显式测试子类的类型.
This is not a very good way to do things in Java, because you are explicitly testing for the type of subclass.
这篇关于如何访问子类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!