问题描述
我目前正在学习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"));
我正在尝试使用以下代码访问Game子类中的方法"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您知道您正在查看 Game
,并进行明确投射:
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.
这篇关于如何访问子类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!