避免在继承的Java类中进行强制转换

编程入门 行业动态 更新时间:2024-10-25 16:20:24
本文介绍了避免在继承的Java类中进行强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一堂课

class MyClass { public MyClass getParent() { ... } public MyClass[] getChildren() { ... } .... }

和一个子类

MySubClass extends MyClass { public String getId() { } ... }

每次我在 MySubClass 的实例上使用 getChildren()或 getParent()时,我都必须转换这些方法的结果,例如:

Everytime I used getChildren() or getParent() on an instance of MySubClass, I have to cast the result of theese methods, e.g.:

MySubClass sub = new MySubClass(); ((MySubClass)sub.getParent()).getId();

是否有任何方法(通过语言或设计)来避免这种转换?

Is there any way (by language or design) to avoid that casting?

感谢任何想法!

更新我想要的是 getParent()和 getChildren()总是返回从中调用它们的实例的类型,例如 sub.getChildren()应该返回 MySubClass []

Update What I would like is that getParent() and getChildren() always return the type of the instance they are called from, e.g. sub.getChildren() should return MySubClass[]

推荐答案

您可以使用自类型模式:

You can use the self-type pattern:

class MyClass<T extends MyClass<T>> { public T getParent() { ... } public List<T> getChildren() { ... } // you can use an array here too, but don't :) } class MySubclass extends MyClass<MySubclass> { public String getId() { ... } }

您可以根据需要实现 getParent 和 getChildren 方法,在 MyClass 中声明包含 T 引用的字段并且知道它们至少表现为 MyClass 引用等.而且,如果您在 MySubClass 上调用 getParent 或 getChildren ,则可以将返回值用作 MySubClass 实例,而无需投射到任何地方.

You can implement your getParent and getChildren methods as desired, declare fields in MyClass that hold T references and know that they behave at least as MyClass references, et cetera. And if you call getParent or getChildren on a MySubClass, you can use the return values as MySubClass instances with no casts anywhere.

这种方法的主要缺点是,以前从未看过它的人会很困惑.

The primary disadvantage of this approach is that people who haven't seen it before tend to get pretty confused.

更多推荐

避免在继承的Java类中进行强制转换

本文发布于:2023-10-28 05:19:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535642.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类中   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!