Friday, September 5, 2014

Default access modifier in Java (or) No access modifier in Java

When we do programming, one of the key points to remember is providing access control to the attributes you are writing. Otherwise you cannot make sure, which is going to be change and which attribute you can have control to write the flow of your algorithm. 

 public class Account{   
  public long amount= 100;   
If you see the above variable amount, you can access anywhere either with in the class, sub classes, even in other packages if you have an instance of Account in your hand. You have no clue who is modifying your money and you cannot have much control on it. See in below case
 public class Account{   
  protected long amount= 100;   
If it is protected, this is a kind of protected state (in a shell), where only with in the class and sub classes can access (SavingsAccount,CurrentAccount etc ..) and for with in the package which is the class present can access it. With in the package means the package that Account class presented.
public class Account{   
  private long amount= 100;   
Where as in case of private, it is strictly accessible only in the current class. No one see the variable out side from class. If anyone still want to expose the private variables value, provide a getter and return the value where there is no way to access the variable outside from the class.
 public class AccessDemo {   
  int instanceCount= 1;   
So, what if one didn't specify the access modifier ?? Compiler treats that as a default modifier aka no modifier. When there is no modifier specify to any of the members in a class, compiler treats that member as a default accessible type member. A default accessible type member is Package Private member. Only with in the Class and with in the Package only you can access that default member. But It is always recommended to specify the access specifier. 

Oracle draw a table in their docs to understand easily and to refer them quickly.
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
The above table copyright belongs to Oracle.

1 comment: