Can we declare the variables of a Java interface private and protected?

Java 8Object Oriented ProgrammingProgramming

Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.

Private fields of an interface

If the fields of the interface are private, you cannot access them in the implementing class.

If you try to declare the fields of an interface private, a compile time error is generated saying “modifier private not allowed here”.

Example

In the following Java example, we are trying to declare the field and method of an interface private.

public interface MyInterface{
   private static final int num = 10;
   private abstract void demo();
}

Compile time error

On compiling, the above program generates the following error

Output

MyInterface.java:2: error: modifier private not allowed here
   private static final int num = 10;
                          ^
MyInterface.java:3: error: modifier private not allowed here
   private abstract void demo();
^
2 errors

Protected fields of an interface

In general, the protected fields can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it.

Therefore, cannot declare the fields of an interface protected. If you try to do so, a compile time error is generated saying “modifier protected not allowed here”.

Example

In the following Java example, we are trying to declare the field and method of an interface protected.

public interface MyInterface{
   protected static final int num = 10;
   protected abstract void demo();
}

Output

MyInterface.java:2: error: modifier protected not allowed here
   protected static final int num = 10;
^
MyInterface.java:3: error: modifier protected not allowed here
   protected abstract void demo();
raja
Published on 04-Jul-2019 14:02:30
Advertisements