Tuesday, October 15, 2013

Access modifiers


Access modifiers are used to set access level to a program. There are four types of levels we are talking about in Java. 
  1. Private
  2. Protected 
  3. Default
  4. Public

We have classes, packages, sub classes and the world in programs. Look at this graph. 



This may help you to understand about access levels.




Now we focus on how to access using these modifiers and where can it be applied.


Try this programs to understand about this theory.


public class Fruit{
   public static void main(String args[ ]){

      Fruit obj1 = new Fruit( ); 
      Apple obj2 = new Apple( ); 
      Mango obj3 = new Mango( ); 
      //Woodapple obj4 = new Woodapple( ); 

      obj1.mix( );
      obj1.extract( );
      obj1.blend( );
      obj2.boil( );
      obj3.fry( );
      //obj4.cool( );
  }

  void mix( ){
      System.out.println("-------|------------|-----------");
      System.out.println(" Class Access method ");
      System.out.println("-------|------------|-----------");
      System.out.println("Fruit--> default----> mix( )");
  }

  private void extract( ){
      System.out.println("Fruit--> private----> extract( )");
  }

  protected void blend( ){
      System.out.println("Fruit--> protected--> blend( )");
  }
}

class Apple{
  void boil( ){
      System.out.println("Apple--> default----> boil( )");
  }
}

class Mango{
  protected void fry( ){
      System.out.println("Mango--> protected--> fry( )");
  }
}

/*
* class Woodapple{
*   private void cool( ){
*       System.out.println("Woodapple--> private--> cool( )");
*   }
* }
*/



In this program my super class is Fruit. There are other two classes named Apple and Mango.
Within my super class it has three methods ( mix, extract, blend ) and main method. each of method has different types of access levels.
  • mix - default
  • extract - private
  • blend - protected
Now you can see that within the same class you can access any access modifier. 

But in this program it is difficult to explain about the behavior with interfaces and packages. Because interfaces are not discussed yet in this series. These things will be discussed later on this blog.

You can try changing access levels in classes also.

In this program I have commented some lines. You can remove comments and see the error message appeared. 


It means that it can't be accessed outside class with 'private' access level.

You can download the code HERE...
Compile and run the program HERE...