Menu
Topics Index
...
`

Derived - Java Example Program


Derived
package packageOne;

class Derived
{
    public static void main(String args[])
    {
        Protection p = new Protection(); // LINE A
        System.out.println("value of i : " + p.i);
        //System.out.println("value of i : " + p.pri_i); // LINE B
        // Raises compilation Error since private cannot be accessed outside of class
        System.out.println("value of pro_i : " + p.pro_i);
        System.out.println("value of pub_i : " + p.pub_i);
    }

}
OUTPUT

value of i : 5
value of pro_i : 15
value of pub_i : 20

DESCRIPTION

In the above program at LINE A we have created an object for Protection class with the reference as p it is possible as both the classes are under the same package. We accessed the member variables of Protection class using the reference p. In the program LINE B is commented since we cannot access the private variables of one class in other class.

THINGS TO TRY
  • Uncomment LINE B it will shows a compilation error, since we cannot access private members outside of the class

© meritcampus 2019

All Rights Reserved.

Open In App