Question

I have a concrete class which extends an abstract class, which in turn extends an abstract class. This top class implements an interface. Can I implement the interface method in the top abstract class, so that the concrete sub-class does not have to?

Also, if the interface method takes an Object type as it's parameter, can I have the implementation in the top abstract class take another type (which seems right to me), or would I have to use exactly the same method signature?

Was it helpful?

Solution

Can I implement the interface method in the top abstract class, so that the concrete sub-class does not have to?

Yes

Also, if the interface method takes an Object type as it's parameter, can I have the implementation in the top abstract class take another type (which seems right to me), or would I have to use exactly the same method signature?

It has to be the same signature. However, you can trick with generics, if you want to and if you explain your plan in more detail.

OTHER TIPS

for your fist quetion

Can I implement the interface method in the top abstract class, so that the concrete sub-class does not have to?

you can and you should if its a common feature for all the subclasses.

below is the example for the same

interface X{
    void show();

}
abstract class A implements X{
    public void show(){
        System.out.println("show");
    }

}

abstract class B extends A{

}

class C extends B{

}

for your second question

No , signature must be same always.

so below program illustares it

interface X{

    void print(Object obj);

}
abstract class A implements X{

    @Override
    public void print(Object obj) {
        System.out.println("print");

    }

}

below program wont compile if you change type in subclass

interface X{

    void print(Object obj);

}
abstract class A implements X{

    @Override
    public void print(A obj) {
        System.out.println("print");

    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top