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.
source to share
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.
source to share