简体   繁体   English

在Java中定义扩展类的属性

[英]Define an attribute that extends a class in java

I have the following class: 我有以下课程:

class Foo {
   public void sayHello(){
       System.out.println("Hello");
   }
}

And I want another class to hold a reference to a class that extends Foo (but can't be Foo). 我希望另一个类持有对扩展Foo的类的引用(但不能是Foo)。 Something like this (erroneous syntax): 像这样(错误的语法):

class Bar {
    private <E extends Foo> E  mFoo;
}

Is that possible? 那可能吗? how can I do it without declaring it in the class name like this? 我怎么能不这样在类名中声明呢?

class Bar <E extends Foo> {
    private  E  mFoo;
}

If you can make Foo an abstract class that might solve it if the main point is that E can't be an instance of Foo. 如果您可以将Foo设为可以解决该问题的抽象类,那么主要要点是E不能是Foo的实例。 If Foo isn't abstract you could still do 如果Foo不是抽象的,您仍然可以

public abstract class AbstractFoo extends Foo {
}

and then declare E to be of type AbstractFoo. 然后声明E为AbstractFoo类型。

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

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