my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding Khalid example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding Khalid example" Watch "Overriding Khalid example" New topic
Author

Overriding Khalid example

Siva Sivaraman
Greenhorn

Joined: Sep 26, 2002
Posts: 17
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

Joined: Sep 26, 2002
Posts: 17
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

Joined: Jul 03, 2001
Posts: 2120
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.


SCJP2. Please Indent your code using UBB Code
Roan Nicolas
Greenhorn

Joined: Nov 11, 2002
Posts: 23
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.


Owee<p>SCJP 1.4
Siva Sivaraman
Greenhorn

Joined: Sep 26, 2002
Posts: 17
Thanks. Understood the concept of 'Variable Shadowing'
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
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".


Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overriding Khalid example