Here is my scenario:
public interface Father{ public void sayHi(); }
public abstract class FatherImpl implements Father{
@Override
public void sayHi() { System.out.print("Hi"); } }
then is the child
public interface Child{}
public class ChildImpl extends FatherImpl implements Child{}
and test function is
Child c = new ChildImpl();
c.sayHi();
This will throw compiling error. Only when i change child interface to
public interface Child{} extends Father
Then the program runs properly.
Anyone can help me explain the reason.
Child c = new ChildImpl();
The Child
interface doesn't have a sayHi()
method, that's in ChildImpl
. You're referencing c
as a Child
object, so you can't access the method.
You could either reference the object as a 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 completely depends on your specific scenario.
The problem is that the compiler cares only the declared type - the type that is assigned is irrelevant.
Applying this to your case, the type Child
has no methods. It doesn't consider that you assigned a ChildImpl
, which does have a sayHi()
method, to the Child
variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.