Addev
Addev

Reputation: 32243

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;
}

Upvotes: 0

Views: 75

Answers (1)

Stochastically
Stochastically

Reputation: 7846

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.

Upvotes: 3

Related Questions