This article discusses a fundamental concept in Java object-oriented concepts –Field Hiding (member variable Hiding).

Can member variables be overridden in Java?

Let’s first take a look at the following example which creates two Sub objects. One is assigned to a Sub reference, the other is assigned to a Super reference. We create two child objects, one using a reference to the child object and one using a reference to the parent object.


public class FieldOverriding {

	public static void main(String[] args) {
		Sub c1 = new Sub();
		Super c2 = new Sub();
		System.out.println(c1.s);
		System.out.println(c2.s);

	}

}

class Super {
	String s = "Super";
}

class Sub extends Super {
	String s = "Sub";
}
Copy the code

The output of the program is:

According to our existing concept of polymorphism, the second should print sub, but it prints super. Why is that?

Member variables are not overridden, but hidden

The definition of a hidden domain in the Java documentation:

Within a class, a field that has the same name as a field in the superclass hides the superclass’s field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super. Generally speaking, we don’t recommend hiding fields as it makes code difficult to read.

This means:

In a class, a member variable in a subclass has the same name as a member variable in a parent class, even if they are of different types. Member variables in the parent class are hidden. In subclasses, member variables of the parent class cannot be accessed simply by reference. Instead, you must obtain the parent’s hidden member variables from a reference to the parent. In general, we don’t recommend hiding member variables because it makes the code hard to read.

In simple terms, subclasses do not override member variables that override the parent class, so access to member variables cannot be polymorphic like access to methods.

A method to access a hidden domain

  • Is to use the reference type of the parent class, and then access the hidden field, as in our example

  • Println ((Super)c1).s); system.out.println ((Super)c1).s);

Translated from www.programcreek.com/simple-java…