interface ursus
{
public void eat();
}
class grizzly implements ursus
{
public void eat() //Line 1
{
System.out.println("Grizzly eats Salmon ");
}
}
class polar implements ursus
{
public void eat() //Line 2
{
System.out.println("Polar eats seals ");
}
}
class ursus_test
{
public static void main(String args[])
{
grizzly g = new grizzly();
polar p = new polar();
p.eat();
g.eat();
}
}
When I remove the access modifier "public" from Line1/Line 2, the compiler complains that I am applying weaker access privileges for the methods "eat()" obtained from the ursus interface.
Does it mean that all methods obtained from interfaces should be only "public" on the classes which implement that interface ?
As per the docs
The public access specifier in the interface indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.
All methods declared in an interface are implicitly public, so the public modifier can be omitted. If you explicitly try to add other access modifier then compiler will complaint.
Methods declared in an interface are by default public. That's why the compiler is complaining. You cannot inherit a public method and then make it protected or private.
Yes, you are right on your assumption. All of the methods that you inherit from an interface should be made public.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With