Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a method must be public?

Consider the following classes:

class A {
    void print() {
        System.out.println("A");
    }
}

class B extends A implements C {
}

public interface C {
    void print();

}

I get this error:

The inherited method A.print() cannot hide the public abstract method in C

Now, I understand that print() must be public in order the eliminate the compilation error, but what's the reason behind this?

like image 363
AngryOliver Avatar asked Jul 04 '14 20:07

AngryOliver


2 Answers

The answer is simple interface methods are always public or else just use composition instead of inheritance. Also to note that while overriding a method you can not narrow down the access level of the method.

The Oracle Docs says:

The access modifier public (§6.6) pertains to every kind of interface declaration.

like image 145
Rahul Tripathi Avatar answered Nov 14 '22 09:11

Rahul Tripathi


B#print can never be truly private, because anyone can call it via the interface:

B b = new B();
C c = b;
c.print();

Java doesn't let you pretend it's private when it is effectively public. (C++ does; different languages make different trade-offs.)

like image 5
Alan Stokes Avatar answered Nov 14 '22 07:11

Alan Stokes