Field hiding

There is a class hierarchy and on each level there is a field with same name publicName.

public class TestCode {
	
	public static void main(String[] args) {
		GrandPa grandPa = new GrandPa();
		System.out.println("Real gradPa name is :" + grandPa.getPublicName());
		
		GrandPa grandPaFatherActually = new Father();
		System.out.println("gradPa type, but father instance:  " + grandPaFatherActually.getPublicName());
		
		GrandPa grandPaSonActually = new Son();
		System.out.println("gradPa type, but son instance:  " + grandPaSonActually.getPublicName());
	}
	
}

class GrandPa {
	private String publicName = "GrandPaName";
	
	public String getPublicName() {
		return publicName;
	}
}

class Father extends GrandPa {
	private String publicName = "FatherName";
	
	public String getPublicName() {
		return publicName;
	}
}

class Son extends Father{
	private String publicName = "SonName";
	
	public String getPublicName() {
		return publicName;
	}
}
Real gradPa name is :GrandPaName
gradPa type, but father instance:  FatherName
gradPa type, but son instance:  SonName

Fields in subclasses can hide fields with the same name in their superclasses. This means that when you access a field using an instance of a subclass, the field in the subclass takes precedence, hiding the fields with the same name in its superclasses.

In the case of your grandPaSonActually instance, which is an instance of the Son class, the field publicName from the Son class takes precedence. So technically, when you access grandPaSonActually.publicName, you are accessing the publicName field from the Son class, and its value is "SonName." This is known as field hiding.

While debuggers may show you the fields from the entire class hierarchy for inspection purposes, the actual field that is accessible and used when you access publicName on grandPaSonActually is the one defined in the Son class. The fields from the superclasses (Father and GrandPa) are effectively hidden in this context.

So, to summarise, only the publicName field from the Son class ("SonName") is technically available and accessible in the grandPaSonActually instance. The fields with the same name in the superclasses are hidden and not accessible through this instance.

Last updated