Access Protection

Java has four type of access specifier private, public, protected and default . There are different access rules for all these access specifier in inheritance.

  • Private data member

    private data member can only be accessed in same class where they are declared. Child class don't have access to parent class private data member.


    Example :

    
    	  
    class base
    {
    private int a;
    }
    class der extends base
    {
    void print()
    {
    System.out.println("a:"+a); // Error: private data can't be accessed.
    }
    }

  • public data member

    public data member of parent class can be accessed in child class.

    Example :

    
    	 //file: base.java
    // www.jgyan.com
    class base
    {
    public int a;
    }
    class der extends base
    {
    void print()
    {
    System.out.println("a:"+a);
    }
    }

    Above program wil be compiled successfully.


  • protected data member

    Protected data member are same as private with one exception that they can be accessed in child class.

    Example :

    
       //file: base.java
    // www.jgyan.com
    class base
    {
    protected int a;
    }
    class der extends base
    {
    void print()
    {
    System.out.println("a:"+a);
    }
    }

    Above program wil be compiled successfully.


  • Default data member

    Default data member are those data member which are not declared with any access specifier. Default data member works same as public in same package. So default data member can be accessed in child class.


    
          //file: base.java
    // www.jgyan.com
    class base
    {
    int a; // Default data member
    }
    class der extends base
    {
    void print()
    {
    System.out.println("a:"+a);
    }
    }

    Above program wil be compiled successfully.


Parent class Child class
Public Can be accessed
Protected Can be accessed
Private Can not be accessed