Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Modifiers on methods obtained from Interfaces

Tags:

java

   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 ?

like image 742
UnderDog Avatar asked Apr 24 '26 17:04

UnderDog


2 Answers

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.

like image 114
Aniket Thakur Avatar answered Apr 26 '26 06:04

Aniket Thakur


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.

like image 23
MD Sayem Ahmed Avatar answered Apr 26 '26 05:04

MD Sayem Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!