铸造问题(可能的解决方法)
好吧,大学给我布置了一项作业,但我就是无法理解这个问题是如何解决的,我是班上唯一一个能做到这一步的人,而我的讲师却没有回复我。
基本上它是关于继承和多态性,我们使用父类,然后从父类创建子类;
private HashMap<String,Aircraft> allAircraft = new HashMap<String,Aircraft>();
Aircraft plane = new Plane(reg,pass,cargo);
所以父母不能使用孩子的方法,我理解这背后的大部分概念,并设法理解它。对于其中一种方法,我们特别被要求使用强制转换(尽管我被告知无数次,如果我必须使用它,那么我应该重组),但对于另一种方法,我们被要求调用一个仅对于两个子类的具体情况,转换在这里不起作用,因为我不知道 HashMap 中的子类是什么。
所以我的问题是;在使用多态性时,我如何比父类更喜欢两个子类方法?
我的头脑简直要爆炸了。
Okay so I've been set an assignment from university and I just can't get my head around how this problem, I'm the only person in the class that's got this far and my lecturer's aren't getting back to me.
Basically it's on inheritance and polymorphism, we are using a parent class and then creating the children from the parent;
private HashMap<String,Aircraft> allAircraft = new HashMap<String,Aircraft>();
Aircraft plane = new Plane(reg,pass,cargo);
So the parent cannot use the children methods, I understand the majority of the concept behind this and have managed to get my head around it. For one of the methods we have specifically been asked to use casting (even though I have been told countless times that if I have to use it then I should restructure) but for the other method we have been asked to call a method which is only specific of two of the children classes, casting won't work here because I don't know what the children classes are in the HashMap.
So my question is; how would I favor two children classes methods over the parent class whilst using polymorphism?
My mind is quite literally exploding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您需要向下转型,那么您就不再使用多态性。如果这就是老师想要的,那么您仍然可以通过测试对象的实际类型是否合适来以一种安全的方式进行向下转换:
如果此方法对于两个子类都是通用的,则可能意味着它们实际上共享相同的接口。所以多态性可以在这里重新发挥作用:
If you need to downcast, then you're not using polymorphism anymore. If that's what the teacher wants, then you may still downcast in a safe way by testing that the actual type of the object is the appropriate one :
If this method is common to both subclasses, it might mean that they in fact share the same interface. So polymorphism could come back into play here :
如果此时无法更改基本/派生层次结构,请查看
instanceof
运算符。If you can't change the base/derived hierarchy at this point, look into the
instanceof
operator.您可以使用
getClass()
方法找出对象的确切类,或者也可以使用instanceof
运算符询问对象是否属于某种类型。不管怎样,向对象询问其特定类并不优雅,但在某些情况下您别无选择。You can find out the exact class of an object by using the
getClass()
method, or alternatively you can ask if an object is of a certain type using theinstanceof
operator. Either way, it's not elegant having to ask an object for its specific class, but in certain cases you have no option.