Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Member Access Rules in Inheritance

A subclass can contain all the members of its superclass, except private members.

The protected and public members of superclass can be accessed by its subclass, present in the same package or different package.

Members of a superclass with no access modifiers can be accessed by subclass present only in the same package.

Example

class Parent3 
{
    public String h = "House";
    private String v = "Car";   // v is private so it can't be accessed by any subclass
    protected String m = "Money";
    String s = "Business_Shares";
}

class Child3 extends Parent3
{
    String b = "Bike";
	
    public void childProperty()
    {
        System.out.println("Child Has :: ");
        System.out.println("\t\t"+h);
        System.out.println("\t\t"+m);
        System.out.println("\t\t"+s);
        System.out.println("\t\t"+b);
    }
}

class MemberAccessDemo 
{
    public static void main(String args[])
    {
        Child3 c = new Child3();
        c.childProperty();	
    }
}

Output

Child Has ::
            House
            Money
            Business_Shares
            Bike

In this program, we have accessed only those fields of a superclass which is public, protected and default (with no access modifiers) but not private.
If we try to access private members (here, v = “Car”) of superclass we’ll get an error because it is not allowed by Java.

 

Leave a reply