Home > database >  Interface for 2 classes of same super class in Java
Interface for 2 classes of same super class in Java

Time:11-09

Is there a way to write an interface whose method gets implemented by classes with the same super class? What I tried was using generic methods.

class person{
    private String name;
    //getter and setter
    .
}


class Student extends Person{
    private int points;
    //getter and setter
    .
}

class Worker extends Person{
    private int salary;
    //getter and setter
    .
}

interface Printer{
    <T extends Person> void print (T person);   
}

class WorkerPrinter implements Printer {

    @Override
    public <T extends Person> void print(T person) {
        System.out.println(person.getName());
        System.out.println(person.getSalary());
    }
}

The compiler cannot resolve person.getSalary() even though the generic type T extends from Person.

I want to use this interface in a similar way with a class StudentPrinter and the implemented Method print(T Person)

So basicly what I want is to use the Interface for different "printerclasses" which are inheriting from Person. This is just an example of course. I want to use this in a bigger example. Is this somehow possible? Does it even make sense?

CodePudding user response:

As @Jon Skeet already suggested (that's why I made this answer a community wiki answer, so feel free to improve further), you might want to make your interface have a generic type parameter T instead of having only a method with generic argument type T. Then you could write:

interface Printer<T extends Person> {
    void print (T person);   
}

class WorkerPrinter implements Printer<Worker> {

    @Override
    public void print(Worker person) {
        System.out.println(person.getName());
        System.out.println(person.getSalary());
    }
}
  • Related