sarasvati sarasvati - 1 month ago 7
Java Question

How to use abstract class' child type as the type of an abstract method's parameter?

Let's say there're 2 classes:


  • Foo
    (an abstract class)

  • Bar
    (a child of Foo)



I want the type of an parameter of an abstract function of
Foo
to match the type of the child class that implements
Foo
(such a class could be
Bar
).

I thought I could use the constrained generic types, but I have no idea how to constrain the type to match the child class.

Example:

abstract class Foo {
public abstract boolean testSth( [Type of the child] obj );
}

class Bar extends Foo {
@Override
public boolean testSth( Bar obj ) { // I need the parameter to be of type Bar
// ...
}
}

Answer

You can obviously, just pass the child type as generic type to parent class:

abstract class Foo<T> {
   // or Foo<T extends Foo<T>>
   public abstract boolean testSth(T obj );
}

class Bar extends Foo<Bar> {
    @Override
     public boolean testSth( Bar obj ) { // I need the parameter to be of type Bar
       // ...
    }
 }