Variable shadowing

Today we’ll look into a rare feature of Java: variable shadowing

First, let’s define what is a shadowed field or method:

A field is considered shadowed when

  • a subclass of its declaring class declares a field with the same name and same
  • a variable having the same name and type is declared in the local scope
  • a method argument/parameter is declared with a same name and type

I Local variable shadowing

public class MyClass
{
	private int count = 10;

	private void localVariable()
	{
		int count = 5;

		System.out.println("count = "+ count);
	}

	public static void main(String[] args)
	{
		MyClass test = new MyClass();
		test.localVariable();
	}
}

The above code will output

count = 5

because the count local variable declared at line 7 shadows the variable count declared at class level. If we want to access the instance variable, we need to add the this keyword.

private void localVariable()
{
	int count = 5;

	System.out.println("count = "+ this.count);
}

 

II Method argument shadowing

This situation is very common even though we do not pay much attention to it. Below is a simple getter definition

private int count;

public void setCount(int count)
{
	this.count = count;
}

The this keyword is mandatory to resolve the ambiguity. Without this, the compiler cannot know whether we are assigning the count method argument value to itself. If you remove the this keyword, you would get a compilation warning anyway.

 

III Superclass field shadowing

Let’s consider the following classes:

public class SuperClass
{
	protected String val = "SUPER_VAL";

	protected void display()
	{
		System.out.println("val = "+this.val);
	}
}

public class ChildClass extends SuperClass
{
	private String val;

	public ChildClass(String value) {
		this.val = value;
	}

	public static void main(String[] args)
	{
		ChildClass child = new ChildClass("CHILD_VAL");
		child.display();
	}

}

The execution gives:

val = SUPER_VAL

The val field has been declared in the SuperClass but is shadowed in the ChildClass because the latter declares another field with same name and type. Although the ChildClass has been instantiated with “CHILD_VAL”, the execution of child.display() gives you “SUPER_VAL”.

The reason is simple. When the child instance is created, there are 2 variables val. The one from SuperClass with value “SUPER_VAL” and the one from ChildClass with injected value “CHILD_VAL” through constructor.

When the display() method is called, since it is define in the SuperClass, it is the val field in the context of SuperClass which is used. Not surprising that the output shows “SUPER_VAL”.

public class ChildClass extends SuperClass
{
	private String val;

	public ChildClass(String value) {
		this.val = value;
		super.val = value;
	}

	public static void main(String[] args)
	{
		ChildClass child = new ChildClass("CHILD_VAL");
		child.display();
	}

}

In the above modified code, we force the value for the hidden val field in SuperClass with super.val = value, and the output gives:

val = CHILD_VAL

Now let’s add another class in the hierarchy

public class AncestorClass
{
	protected String val = "ANCESTOR_VAL";
}

public class SuperClass extends AncestorClass
{
	protected String val = "SUPER_VAL";
}

public class ChildClass extends SuperClass
{
	private String val = "CHILD_VAL";

	public void displayVal()
	{
		System.out.println("val = " + super.val);
	}

	public static void main(String[] args)
	{
		ChildClass child = new ChildClass();
		child.displayVal();
	}
}

Obviously, the output will display

val = SUPER_VAL

The question now is: what if we want to display the val value of AncestorClass ? Obviously the super keyword only refers to the first parent class up in the class hierarchy.

Casting comes to the rescue. Indeed we can force the this keyword representing the current class instance to a particular type in the class hierarchy !

public class ChildClass extends SuperClass
{
	private String val = "CHILD_VAL";

	public void displayVal()
	{
		System.out.println("val = " + ((AncestorClass) this).val);
	}

	public static void main(String[] args)
	{
		ChildClass child = new ChildClass();
		child.displayVal();
	}
}

This time, we do have

val = ANCESTOR_VAL

 
 

Advertisements

About DuyHai DOAN
Cassandra Technical Evangelist. LinkedIn profile : http://fr.linkedin.com/pub/duyhai-doan/2/224/848. Follow me on Twitter: @doanduyhai for latest updates on Cassandra

One Response to Variable shadowing

  1. Amazing Post. Thank you a hundred and more times.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: