避免在继承的Java类中进行强制转换 [英] Avoid casting in inherited java-classes

查看:52
本文介绍了避免在继承的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类中进行强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆