将超类的对象转换为子类 - 向下转换 [英] Cast an object of super class to a sub class - down casting
问题描述
我知道只能从子类到超类(向上转换)进行转换,但这个例子说明了我想要做的事情。
I know that casting can really only be done from a sub class to a super class (up casting) but this example illustrates what I would like to do.
Class Super {}
Class Sub extends Super {}
Super super = new Super();
Sub sub = (Sub)super;
我认为这被称为向下投射,这是不允许的......
I believe this is referred to as "down" casting which is not allowed so...
在给定Super类型的对象的情况下,创建Sub类型对象的最佳方法是什么。
What is the best way to create an object of type Sub given an object of type Super.
编辑:
这就是问题 - 将动物转换成猫的最佳方法是什么。
That's the question - What's the best way to convert an Animal to a Cat.
答案是什么?从基类动物开始,将属性复制到cat。添加毛发和尾巴等基本上是一个复制构造函数。这是正确的答案(或一个好的答案)吗?
The answer? Start with a base type animal and copy the attributes to the cat. Add fur and a tail, etc. Basically a copy constructor. Is this the right answer (or a good answer)?
另一个编辑:
我想我的问题是很清楚但也许它太笼统了。要求最好的做事方式往往会产生很多不同的反应。我意识到在不同情况下最好的方法可能会有所不同。
I think my question is pretty clear but maybe it is too general. Asking for the "best" way to do something tends to give a lot of varying responses. I realize the best way can be different in different circumstances.
我不是在寻找有关Java或OO基础知识的教程。只是捕获意见所以我可以解决这个问题,因为我已经使用最佳实践概述了它。
I'm not looking for a tutorial on Java or OO basics. Just fishing for opinions so I can solve this problem as I have outlined it using best practices.
推荐答案
A 猫
是动物
。
如果我给你一只动物(没有'必须是猫),你怎么把它转换成猫?
If I give you an animal (doesn't have to be cat), how would you convert it to a cat?
编辑:
有一个做几乎任何事情的方法。大多数时候,你不应该。我相信更好的设计将消除向下转型的需要。但你可以:
There's a way to do almost anything. Most of the time, you shouldn't. I believe a better design would eliminate the need for downcasting. But you can:
-
在
超级
中有一个构造函数Sub
作为参数。
have a constructor in
Super
that takes aSub
as parameter.
实施超级$ c的工厂$ c>并且有一个方法需要
Sub
作为参数。
implement a factory of Super
and have a method that takes a Sub
as parameter.
我建议你扩展你的问题,告诉我们你需要什么,因为我认为存在一个更优雅的解决方案。
I suggest that you expand your question, tell us exactly what you need, as I really think a more elegant solution exists.
这篇关于将超类的对象转换为子类 - 向下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!