简体   繁体   中英

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). 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. If Foo isn't abstract you could still do

public abstract class AbstractFoo extends Foo {
}

and then declare E to be of type AbstractFoo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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