Extend override method from abstract class in java

Here's my scenario:

public interface Father{ public void sayHi(); }
public abstract class FatherImpl implements Father{
   @Override
   public void sayHi() { System.out.print("Hi"); } }

      

then this is a child

public interface Child{}
public class ChildImpl extends FatherImpl implements Child{}

      

and test function

Child c = new ChildImpl();
c.sayHi();

      

This will cause a compilation error. Only when I change the child interface to

public interface Child{} extends Father

      

Then the program works correctly.

Anyone can help me explain the reason.

+3


source to share


2 answers


Child c = new ChildImpl();

      

The interface Child

has no method sayHi()

, which is in the ChildImpl

. You are referring to c

as an object Child

, so you cannot access this method.

You can refer to the object as ChildImpl

or add another class.

ChildImpl c = new ChildImpl();

      

or



public abstract class TalkingChild {
    @Override
    public void sayHi() {
        System.out.print("Hi");
    }
}

      

or



public interface TalkingChild {
    public void sayHi();
}

      

The best solution depends entirely on your specific scenario.

+3


source


The problem is that the compiler only cares about the declared type - the assigned type doesn't matter.



Applying this to your case, the type Child

has no methods. It doesn't think you assigned ChildImpl

which method has sayHi()

to a variable Child

.

+2


source







All Articles