Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding Khalid example

 
Siva Sivaraman
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Light{
protected String billType ="Small bill";
}
class TubeLight extends Light{
public String billType="Large bill";
}
public class Client{
public static void main(String args[])
{
Light lightRef1=tubeLightRef;
System.out.println(lightRef1.billType);
}
}
Output:
Small bill
I expected "Large bill" here in this upcasting as lightRef1 denotes the Tubelight Object.Please explain.
 
Siva Sivaraman
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see this...Missed the instance of TubeLight in the previous one.
class Light{
protected String billType ="Small bill";
}
class TubeLight extends Light{
public String billType="Large bill";
}
public class Client{
public static void main(String args[])
{
TubeLight tubeLightRef=new TubeLight();
Light lightRef1=tubeLightRef;
System.out.println(lightRef1.billType);
}
}
Output:
Small bill
I expected "Large bill" here in this upcasting as lightRef1 denotes the Tubelight Object.Please explain.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fields does not exhibit polymorphic behaviour. The class to be searched for the field, is the type of the reference of lightRef1, that is Light. Because it is looking for a field the JVM does not search subclasses.
 
Roan Nicolas
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When a variable of an object (billType) is accessed using a reference, it is the type of reference (Light), not the class of the current object (TubeLight) that determines which variable will actually be accessed.
Hope that makes sense.
 
Siva Sivaraman
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. Understood the concept of 'Variable Shadowing'
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Siva Sivaraman:
Thanks. Understood the concept of 'Variable Shadowing'

A subclass variable "hides" a superclass variable. A local variable "shadows" a member variable. Within the scope of the shadowing variable the "shadowed" variable can be accessed using the keyword "this".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic