vcmkrtchyan
vcmkrtchyan

Reputation: 2626

Class must be declared as abstract or implement abstract method

I have one class and two interfaces

public class A implements B, C {
    public static void main(String[] args) {
        A a = new A();
        a.foo();
    }
}

public interface B {
    default void foo(){
        System.out.println("foo in B");
    }
}

public interface C {
    void foo();
}

The thing i'm concerned about is that java doesn't compile this giving an error that I must implement method from C. Hence I have a question. Why doesn't the default body cover that part, I mean the only thing java must be concerned about is that all the methods have their implementations, right? But for the class A, it's obvious that the implementation is given in B.

So why is java giving that error?

Upvotes: 3

Views: 899

Answers (1)

hagrawal7777
hagrawal7777

Reputation: 14668

This is because interface B and C are not in same inheritance tree. And if they are not then Java compiler cannot be sure that implementing class has implementation of all methods of interface until it checks for each method from each implementing interface.

If you will define interface C as public interface C extends B then you will not get the error because in this case Java compiler will be sure that all methods are implemented.

Read more from JLS §9.4.1. Inheritance and Overriding

Upvotes: 3

Related Questions