简体   繁体   English

我可以在Java中将扩展类中的可变类型强制为子类型吗?

[英]Can I force the type of a variabile in a extended class to a subtype in Java?

Having this: 有这个:

public class A{}
public class B extends A{}
public class C{
    protected A x;
}

Is there any way to create a class D which extends C such that the type of x must be B in all D's instances? 有什么方法可以创建扩展C的类D,以便在所有D实例中x的类型都必须为B Note that C is a class I'm writing, so I could edit it on purpose to accomplish D needs. 请注意,C是我正在编写的类,因此我可以有目的地对其进行编辑以满足D的需要。

Use generic type 使用通用类型

public class C<T>{
    protected T x;
}

public class D extends C<SomeConcreteType>{
     //x will be SomeConcreteType
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM