我正在做一个自动取款机的项目,它要求我使用多态概念。
我有一个问题:
假设我有一个代表所有哺乳动物的接口,然后我创建了以下子类: Human。 想象一下,现在我想在我的程序中创造一些人类和一些鲸鱼,我会把它们保存在一组哺乳动物中。
问题是,子类Human有solveMathProblem()方法,而Whale类没有它,因此哺乳动物也没有。
如何在数组中使用该方法?(例如:mammals[2].solveMathProblem();)
因为哺乳动物界面中没有指定solveMathProblem(),因为只有人类才能这样做)
我能做些什么才能让它发挥作用?
发布于 2015-04-04 12:56:12
子类对象的超类引用不能访问超类中未定义的方法。
您需要显式地将哺乳动物引用转换为人类引用,以便能够访问存在于人中的方法,如下所示:
((Human)mammals[2]).solveMathProblem();尽管如此,您应该看看如何通过组合添加行为的策略模式。这的回答在解释这个概念方面做得很好。在特定情况下,通过引入新的行为层次结构,可以向不同的Mammal实现添加不同的行为。
发布于 2015-04-04 12:57:46
为什么不在调用solveMathProblem方法之前在循环中使用instanceof操作符。
发布于 2015-04-04 13:05:12
我可以想到两种方法,这两种方法都可能是好的:
solveMathProblem声明为Mammal interface- declare the method for the `interface`
- create a `class`, called `MammalCore`
- `implement` the method of `solveMathProblem` in `MammalCore` in a way that it would throw an exception, which will state that the operation is unsupported (this way it will be a default behavior)
- override `solveMathProblem` for `Human` This way, if you call solveMathProblem in your array, exception will be thrown for Whale instances and it will be accurately executed for Human instances
solveMathProblem (如何检查Java运行时是否存在方法?),如果存在,则检查方法是否存在。https://stackoverflow.com/questions/29446609
复制相似问题