Hiding instance variables of a class Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Hiding instance variables of a class without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m wondering why Java has this strange behavior regarding a superclass and a subclass having instance variables with the same name.

Let’s say we have the following class definitions:

class Parent {
    int var = 1;
}

class Child extends Parent {
    int var = 2;
}

By doing this, we are supposed to have hidden the superclass’s variable var. And if we do not explicitly specify a way to access Parent‘s var via a super call, then we should never be able to access var from an instance of a child.

But when we have a cast, this hiding mechanism breaks:

Child child = new Child();
Parent parent = (Parent)child;
System.out.println(parent.var); // prints out 1, instead of 2

Doesn’t this completely circumvent the whole point of field hiding? If this is the case, then doesn’t that render the the idea completely useless?

EDIT: I am referring specifically to this article in the Java Tutorials. It mentions

Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super…

From what I read there, it seems to imply that the developers of Java had some kind of technique in mind in doing this. Though I agree that it is a rather obscure concept and would probably bad practice in general.

Answer

In Java, data members are not polymorphic. This means that Parent.var and Child.var are two distinct variables that happen to have the same name. You’re not in any sense “overriding” var in the derived class; as you have discovered yourself, both variables can be accessed independently of one another.

The best way forward really depends on what you’re trying to achieve:

  1. If Parent.var should not be visible to Child, make it private.
  2. If Parent.var and Child.var are two logically distinct variables, give them different names to avoid confusion.
  3. If Parent.var and Child.var are logically the same variable, then use one data member for them.
We are here to answer your question about Hiding instance variables of a class - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji