In Java, when both a parent class and a child class declare a data member with the same name, the child’s data member hides the parent’s data member. This concept is known as data hiding (variable hiding) and is different from method overriding.
- Data members are not overridden in Java; they are hidden.
- Access to the data member depends on the reference type, not the object type.
- Both parent and child maintain separate copies of the data member.
- Parents’ data member can be accessed using the super keyword.
Example: Parent and Child with Same Data Member
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
}
public class Main {
public static void main(String[] args) {
Parent p = new Child();
Child c = new Child();
System.out.println(p.x);
System.out.println(c.x);
}
}
Output
10 20
Explanation:
- Parent and Child both declare a data member named x.
- p.x accesses the data member of the Parent class because the reference type is Parent.
- c.x accesses the data member of the Child class because the reference type is Child.
- This shows that data member access is resolved at compile time.
Accessing Parent Data Member Using super
class Child extends Parent {
int x = 20;
void show() {
System.out.println(x); // Child's x
System.out.println(super.x); // Parent's x
}
}
Explanation:
- x refers to the child’s data member.
- super.x explicitly accesses the parent’s data member.
Difference Between Method Overriding and Data Member Hiding
Feature | Method Overriding | Data Member Hiding |
|---|---|---|
Applies to | Methods | Variables |
Resolution | Runtime (Dynamic Binding) | Compile-time |
Polymorphism | Supported | Not supported |
When to Avoid Same Data Members
- When it causes confusion in large codebases
- When readability and maintainability are priorities
Variable access in Java depends on the reference type, whereas method calls depend on the object type.