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?

有帮助吗?

解决方案

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.

其他提示

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");

    }

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top