This is a modified example taken from Professor Khalid's book. The output is:
Large bill
Small bill
Small bill
My question is why Small bill is printed even if the the object to which light1 refers to is of type TubeLight. Shouldn't TubeLight's method be called? Isn't that the basis of
polymorphism?
Here is the example the question is about:
class Light {
protected static
String billType = "Small bill";
public static void printBillType() {
System.out.println(billType);
}
}
class TubeLight extends Light {
public static String billType = "Large bill";
public static void printBillType() {
System.out.println(billType);
}
}
public class Client {
public static void main(String[] args){
TubeLight tubeLight = new TubeLight();
Light light1 = tubeLight;
Light light2 = new Light();
tubeLight.printBillType();
light1.printBillType(); // Shouldn't this print Large Bill
light2.printBillType();
}
}
/* Below are the classes I have written, and they give me the expected
output: In Class Two
What is the difference then between the above class written by Prof.
and below written by me?
*/
class One
{ public void put()
{ System.out.println("In class One"); }
}
class Two extends One
{ public void put()
{ System.out.println("In class Two"); }
public static void main(String[] args)
{ Two two_type = new Two();
One one_type = two_type;
one_type.put(); // It prints In class Two as expected
}
}