Menu
Topics Index
...
`

Protectiontwo - Java Example Program


Protectiontwo
package packageTwo;

class Protectiontwo extends packageOne.Protection
{
    public static void main(String[] args)
    {
        Protectiontwo newp = new Protectiontwo(); // LINE A
        //System.out.println("value of i : " + newp.i);
        //Raises compilation error since default access specifier can accessed within same class or package
        //System.out.println("value of pri_i : " + newp.pri_i);
        System.out.println("value of pro_i : " + newp.pro_i); // LINE B
        //protected works in the subclass of different package
        System.out.println("value of pub_i : " + newp.pub_i); // LINE C
        //public can be accessed as it doesn't have any restrictions
    }
}
OUTPUT

value of pro_i : 15
value of pub_i : 20

DESCRIPTION

In the above program at LINE A we have created an object for Protectiontwo class with the reference as newp as Protectiontwo extends packageOne.Protection it becomes subclass for packageOne.Protection. In the above program at LINE B newp.pro_i is accessible, since Protectiontwo is a subclass for packageOne.Protection.

THINGS TO TRY
  • Create object for Protection class with reference np and access it's member variables
    In that case np.pro_i is not accessible because the object is created for Protection class.

© meritcampus 2019

All Rights Reserved.

Open In App