关于java中的虚方法的问题
简而言之:我希望以下代码打印“sub”:
Element e = new SubElement();
print(e);
...
private static void print(Element e) {
System.out.println("e");
}
private static void print(SubElement e) {
System.out.println("sub");
}
并且我不想更改 print(Element e)。所以
private static void print(Element e) {
if (e instanceof SubElement) {
print((SubElement) e);
} else {
System.out.println("e");
}
}
我想做的就是
print(e.getClass().cast(e));
自动将其转换为真正的子类并强制系统输入 print(SubElement e)。这有可能吗?
Put simply: I want the following code to print "sub":
Element e = new SubElement();
print(e);
...
private static void print(Element e) {
System.out.println("e");
}
private static void print(SubElement e) {
System.out.println("sub");
}
and i dont want to change print(Element e). so nothing like
private static void print(Element e) {
if (e instanceof SubElement) {
print((SubElement) e);
} else {
System.out.println("e");
}
}
what i would like to do is
print(e.getClass().cast(e));
to automatically cast it to the real subclass and force the system to enter print(SubElement e). is this somehow possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
运行的重载方法是在编译时选择的,这就是选择 Element 版本而不是 SubElement 版本的原因。看起来更合乎逻辑的是让 Element 或子类包含应打印的数据。
然后在 print 方法中:
这是否有意义将取决于
Element
类实际上是什么以及打印的数据表示什么。The overloaded method that is run is chosen at compile time so that is why the Element version is chosen rather than the SubElement version. What would seem more logical would be to have the Element or subclass contain the data that should be printed.
and then in the print method:
Whether this is going to make sense will depend on what the
Element
class actually is and what the printed data represents.是的。您可以使用访客模式。然而,它适用于已建立的定义良好的层次结构,因为您必须定义的 Visitor 接口需要每种类型都有一个方法。
Yes. You can use Visitor pattern. However it's suitable for stablished well-defined hierarchies, because the Visitor interface you have to define needs a method for each type.
print()
确实需要成为Element
的实例方法。否则,您将尝试以困难的方式模仿多态性。如果您希望这样做,您实际上无法避免一系列从Class
到函数对象的映射的if
语句。何苦呢?print()
needs to become an instance method ofElement
, really. You're trying to imitate polymorphism in a hard way otherwise. If you wish to do that, you can't really avoid some series ofif
statements of mappings fromClass
to function objects. Why bother?您能够将行为差异推入元素类中吗?
这样,
SubElement
就可以重写getMessageToPrint()
方法。或者更好的是:
Are you able to push the difference of behaviour into the element classes?
This way,
SubElement
can override thegetMessageToPrint()
method.Or better still:
我会选择不同的方法。要么
基类
派生类
打印元素的帮助器接口
为给定元素获取最佳 PrintHelper 的工厂
客户端测试类,作为 Java 应用程序运行< /strong>
输出
I would choose a different approach. Either
Base Class
Derived Class
Helper Interface to print elements
Factory to get the best PrintHelper for a given element
Client test class, run as Java Application
Output