zzyclark
zzyclark

Reputation: 161

extend an override method from abstract class in java

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.

Upvotes: 3

Views: 78

Answers (2)

Bohemian
Bohemian

Reputation: 424973

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.

Upvotes: 2

Anubian Noob
Anubian Noob

Reputation: 13596

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.

Upvotes: 3

Related Questions