field hiding in java
Field hiding in Java refers to the phenomenon where a subclass declares a field with the same name as a field in its superclass. This causes the field in the subclass to “hide” the field in the superclass, meaning that references to the field name within the subclass will refer to the subclass’s field rather than the superclass’s field. Here’s a breakdown of field hiding in Java:

Table of Contents
- 1. Declaring Fields:
- When a subclass declares a field with the same name as a field in its superclass, it hides the superclass’s field.
- Both the superclass and subclass fields can coexist, but their visibility depends on the context of access.
- 2. Accessing Fields:
- Within the subclass, references to the field name will refer to the subclass’s field by default, hiding the superclass’s field.
- To access the superclass’s field from within the subclass, you can use the `super` keyword.
- 3. Visibility:
- The visibility of the fields in the superclass and subclass remains unchanged.
- If the superclass’s field is `private`, it cannot be accessed directly from the subclass.
Example:
Consider a superclass `Parent` and a subclass `Child`, both of which have a field named `value`:
```java
class Parent {
int value = 10;
}
class Child extends Parent {
int value = 20;
void display() {
System.out.println("Child's value: " + value); // Refers to Child's value (hiding Parent's value)
System.out.println("Parent's value: " + super.value); // Refers to Parent's value
}
}
```
In this example:
- The `Child` class declares a field `value` with the same name as the `value` field in its superclass `Parent`.
- The `display` method in the `Child` class demonstrates accessing both the subclass’s `value` and the superclass’s `value` using the `super` keyword.
Importance:
Field hiding can lead to confusion if not used carefully. It’s essential to understand which field is being referenced, especially when accessing fields within methods or constructors of the subclass. Proper usage of field hiding can help maintain code clarity and prevent unintended behavior caused by inadvertently hiding superclass fields.