Is it possible to define an interface like this:
public interface Test{
public string name1;
private String email;
protected pass;
}
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.
Note: We cannot declare class/interface with private or protected access modifiers.
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.
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.
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
Interfaces cannot be instantiated that is why the variable are static
Interface are used to achieve the 100% abstraction there for the variable are final
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
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