Java-Superclass with Private Variables

Superclass with Private Variables

Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private. When a members of a class is specified as private, then that member can only be accessed by other members of its class. This is the highest degree of protection.

In the following program, the NewData class is doesn’t directly access the data1 and data2 variables, because the data1 and data2  is declared by private, it is only accessible by other members of its own class.


Program Source

class Data {
    private int data1;
    private int data2;
    void setData(int da1,int da2)
        data1 = da1;
        data2 = da2;
    int getData1()
        return data1;
    int getData2()
        return data2;

class NewData extends Data{
    int data3;
    int data4;
    void setNewData(int da1,int da2,int da3,int da4)
        data3 = da3;
        data4 = da4;
    void showNewData()
        System.out.println("data1 = "+getData1());
        System.out.println("data2 = "+getData2());
        System.out.println("data3 = "+data3);
        System.out.println("data4 = "+data4);

public class Javaapp {

    public static void main(String[] args) {
        NewData obj = new NewData();
        obj.setNewData(20, 40, 60, 80);

Leave a Comment