Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use private or protected member variables in an interface?

Tags:

java

Is it possible to define an interface like this:

public interface Test{
   public string name1;
   private String email;
   protected pass;
}
like image 706
Tamanna Iruu Avatar asked Mar 25 '15 11:03

Tamanna Iruu


People also ask

Can we define private or protected variables in interfaces?

No, it is not possible to define private and protected modifiers for the members in interfaces in Java. As we know that, the members defined in interfaces are implicitly public or in other words, we can say the member defined in an interface is by default public.

Can you declare private and protected modifiers for variables in interfaces?

Note: We cannot declare class/interface with private or protected access modifiers.

Can we use private and protected access modifiers inside an interface?

Interface Access Modifiers Java interfaces are meant to specify fields and methods that are publicly available in classes that implement the interfaces. Therefore you cannot use the private and protected access modifiers in interfaces.

Can we use protected modifier in interface?

The java language specification doesn't currently allow the protected modifier for interface methods. We can take advantage of this fact and use protected for interface methods for this new feature.


1 Answers

When you Declare interface The java compiler adds public and abstract keywords before the interface methods and public, static and final keywords before data members automatically

public interface Test{
   public string name1;
   private String email;
   protected pass;
}

as you have declare variable in test interface with private and protected it will give error. if you do not specify the modifier the compiler will add public static final automatically.

public interface Test{
   public static final string name1;
   public static final  String email;
   public static final pass;
}

The most important thing is that

  1. Interfaces cannot be instantiated that is why the variable are static

  2. Interface are used to achieve the 100% abstraction there for the variable are final

  3. An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them. that is why variable are public

like image 139
Varun Avatar answered Sep 23 '22 09:09

Varun