Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generic class extends parametrized type

Tags:

java

Assume the following existing classes:

class A { 
  public void foo() { ... };
  ...
}

class A1 extends A  { ... };
class A2 extends A  { ... };
...
class A1000 extends A  { ... };

now, we need to create a variant of each Axx class that overrides "foo" method. The basic idea was:

class B<T extends A> extends T {
  @Override public void foo () { ... };
}

But it seems is not posible to extend a class from one of their parametized types.

The objective is to skip the need of following new code:

class B1 extends A1 { @Override public void foo() { ... }; }; 
class B2 extends A2 { @Override public void foo() { ... }; }; 
....
class B1000 extends A1000 { @Override public void foo() { ... }; };

and allow statements like:

... 
B<A643> b643 = new B<A643>; 
b643.foo(); 
...

Any hint?

Thanks a lot.

like image 692
pasaba por aqui Avatar asked May 11 '15 10:05

pasaba por aqui


2 Answers

A isn't generic. I think you wanted something like,

class B<T> extends A {
  @Override public void foo () { ... };
}

That is a generic type B that extends A... T extends A would mean B takes a type that extends A (not B extends A).

like image 129
Elliott Frisch Avatar answered Oct 04 '22 09:10

Elliott Frisch


You can mix inheritance with delegation. I'd consider it ugly, but it should work.

class UniversalB extends A{
 A a;
 UniversalB(A a) {
    this.a = a;
 }

 @Override public void foo() { ... };

 // @Override any other method from A you want/need
 // and delegate it to the passed member if necessary

}

UniversalB b = new UniversalB(new A123());
b.foo();
b.anyMethodInA();
like image 27
Dariusz Avatar answered Oct 04 '22 07:10

Dariusz