N J
N J

Reputation: 33

How to make method generic when using inheritance in Java?

I have class Employee and 3 classes that extends Employee class. I also have EmployeeService interface where i want to have only one save method to handle saving each type of Employee. So i assumed that it could be solved using generics. This is what i tried in EmployeeService interface:

public interface EmployeeService {
<SubRequestT extends  Employee>EmployeeResponse save(SubRequestT requestT);
}

And class that provide implementation:

@Service
public class EmployeeServiceImpl implements EmployeeService {

// So here in argument i want to have to put any kind of Employee, for example:
@Override
public EmployeeResponse save(OfficeEmployee requestT) {
// Logic for saving employee
    return null;
}
}

But when i changed from Employee type to any other, for example OfficeEmployee who is extending from Employee, complier is giving me an error. What is best way to solve this?

Upvotes: 2

Views: 50

Answers (1)

xerx593
xerx593

Reputation: 13261

With "method generics" I (me & compiler) also struggle, but with "type generics" we can do that!

Assuming:

class Foo {/*...*/}

class Bar extends Foo {}

class Baz extends Foo {}

// extending your question to two generic parameters:
class FooResult {}

class BarResult extends FooResult {}

class BazResult extends FooResult {}

When we define our interface like:

interface FooI<I extends Foo, R extends FooResult> { //or with even more (fixed size) "generic parameters"
  R save(I request);
}

We can override it like:

class BarImpl implements FooI<Bar, BarResult> {
  @Override
  public BarResult save(Bar bar) {
    // ...
    return ...;
  }
}

class BazImpl implements FooI<Baz, BazResult> {
  @Override
  public BazResult save(Baz baz) {
    // ...
    return ...;
  }
}

Upvotes: 2

Related Questions