Shady Xu
Shady Xu

Reputation: 5865

Why does inherited public method manipulate the super class's private property instead of the child class?

In the code below, when I run Test2, why does it print null instead lol? It seems that the config method modifies the a property of class Test instead of Test2.

But what's the meaning of inheriting the public methods which manipulate private properties then, why did they design Java like this?

EDIT:

Class Test shall not be modified. What I want to do is to reuse the config method. I define a private property a for Test2, but config just ignores it and uses the one of Test. Shouldn't a method use the property of the class it is in instead of that of the inherited super class?

public class Test {
    private String a;

    public void config() {
        a = "lol"
    }
}

public class Test2 extends Test {
    private String a;

    public void print() {
        config();
        System.out.println(a);
     }

    public static void main(String[] args) {
       print()
    }
}

Upvotes: 0

Views: 145

Answers (2)

Radiodef
Radiodef

Reputation: 37845

It seems that the config method modifies the a property of class Test instead of Test2.

That's right.

why does it print null instead lol?

You have two variables with the same name. One is in the superclass Test, another is in the subclass Test2. Both are named a but they refer to different things.

The method config() in the superclass references the superclass a and the print() method in the subclass references the subclass a. Since the variables are private, neither method can see the variable in the other class.

why did they design Java like this?

This is the nature of private. Nobody else can see it.

It looks to me like you actually desired the behavior of a protected variable:

public class Test {
    protected String a;

    public void config() {
        a = "lol"
    }
}

public class Test2 extends Test {
    public void print() {
        config();
        System.out.println(a);
    }

    public static void main(String[] args) {
       new Test2().print();
    }
}

This will print lol.

Upvotes: 1

univerio
univerio

Reputation: 20518

The purpose is, in short, encapsulation. You don't need to, and can't, access something that is private from outside of the class. The accepted pattern of doing what you want is with getters/setters:

public abstract class Test {
    public void config() {
        setA("lol");
    }

    public abstract void setA(String value);
}

public class Test2 extends Test {
    private String a;

    public void setA(String value) {
        a = value;
    }

    public void print() {
        config();
        System.out.println(a);
     }

    public static void main(String[] args) {
       new Test2().print();
    }
}

Upvotes: 1

Related Questions