RamValli
RamValli

Reputation: 4485

this operator and private variable in inheritance

I have a class called Parent which has a private variable and a method named display to display that variable value. In a class called Child , parent is inherited.

    public class GoodDay {
        public static void main(String[] args) {
            new Child().display();
        }
    }

    class Parent
    {
        private int i=5;
        public void display()
        {
            System.out.println(this.i +" "+this.getClass());
        }
    }

    class Child extends Parent
    { }

Output 5 class p1.Child

1) this.getClass() gives p1.Child as the value. So this display method is a inherited method copy which is available in the Child class. Then how can it access the Parent class private variable without using public getter and setter?
2) Why this keyword in this.i doesn't give any error as there is no i in child class?

I checked this link and it says that even the private variables are available in the child class objects and not in child class. How and Why ?

Upvotes: 0

Views: 141

Answers (2)

vikingsteve
vikingsteve

Reputation: 40388

1) Ok, the display() method is visible in the Child class due to the public access modifier. The instance variable i isn't accessible directly e.g. new Child().i, but it's perfectly fine to access it "via" a call to display() - this is by intention of object oriented design.

The purpose of access modifiers (there are four of them in java: public, protected, package-private and private) is to limit how and exactly where a member (such as an instance variable or a method) can be directly accessed. This promotes better design, through principles like encapsulation.

So just because an int is private doesn't mean it can't be accessed indirectly by another class - it only can't be accessed directly. If you expose your int to the outside world via a public method, that's completely fine, since the public method of a class can access all of the private members of the same class.

2) this.i doesn't give an error because it is referred to in the context of the Parent class (not Child).

By the way you can avoid this. in most cases. Try this, it's the same.

    System.out.println(i +" " + getClass());

And thirdly, why does it print class p1.Child, when the code executes from the Parent class? Simple, because getClass() is overloaded by every class, and via polymorphism and method overloading / dynamic dispatch you are executing the getClass() (and, via the print statement, implicitly the toString() method from that...) from the Childclass.

Does this make things any clearer?

Upvotes: 1

Héctor
Héctor

Reputation: 26054

If Child doesn't override the display() method, because of polymorphism super.display() method, that is Parent display() method. If you want to access to i variable in Child class, you must declare protected this variable, instead of private.

Upvotes: 0

Related Questions