Can we change the access specifier from (public) while implementing methods from interface in Java?


An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.

To create an object of this type you need to implement this interface, provide a body for all the abstract methods of the interface and obtain the object of the implementing class.

All the methods of the interface are public and abstract and, we will define an interface using the interface keyword as shown below −

interface MyInterface{
   public void display();
   public void setName(String name);
   public void setAge(int age);
}

Implementing the methods of an interface

While implementing/overriding methods the method in the child/implementing class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception.

Since the public is the highest visibility or lowest access restriction and the methods of an interface are public by default, you cannot change the modifier, doing so implies increasing the access restriction, which is not allowed and generates a compile-time exception.

Example

In the following example we are inheriting a method from an interface by removing the access specifier “public”.

 Live Demo

interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   public static int num = 10000;
   void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      MyInterface.num = 200;
   }
}

Output

Compile-time error −

On compiling, the above program generates the following compile-time error.

InterfaceExample.java:7: error: display() in InterfaceExample cannot implement display() in MyInterface
   void display() {
         ^
attempting to assign weaker access privileges; was public
InterfaceExample.java:14: error: cannot assign a value to final variable num
   MyInterface.num = 200;
               ^
2 errors
raja
Published on 10-Sep-2019 14:13:28
Advertisements