Larry
Larry

Reputation: 11919

Extend generic class for certain kinds of types?

If say I have some generic class, for example:

public class Attribute<T> {

}

Is it possible now to have specific methods for specific types? I.e. to extend the generic class for certain kinds of types?

For example:

I want to add extra methods to Attribute<String>, but not for say Attribute<Integer>.

Upvotes: 3

Views: 1364

Answers (4)

gcesarmza
gcesarmza

Reputation: 301

Your class should be abstract:

public abstract class Attribute<T> {
  void someMethod(T object);
}

And then add subclasses such as:

public AttributeString<T extends String> extends Attribute<T>{
    void someMethod(T object){
    }
}

Upvotes: 0

Paulius Matulionis
Paulius Matulionis

Reputation: 23415

You can do something like this:

public abstract class Attribute<T> {
    public abstract T getValue();
}

public class Attr1 extends Atrribute<String> {

   @Override 
   public String getValue() {
      return "smth"
   }
}

Create an abstract class which will have the generic type T and abstract method with the same generic type. Then other classes can extend it by specifying real object instead of generic.

Upvotes: 2

Vlad
Vlad

Reputation: 35594

There is no such direct possibility in Java.

But you can have StringAttribute that extends Attribute<String> and adds to it the methods you'd like to. You can make a kind of factory, in a dependency injection fashion, which will construct e.g. Attribute<Integer> for Integer and StringAttribute for String.

Upvotes: 3

Jim Garrison
Jim Garrison

Reputation: 86774

Not directly, but you can do this...

public class StringAttribute extends Attribute<String>
{
    public String myNewMethod() ...
    ....
}

Upvotes: 2

Related Questions