}
public static void main(String args[]) {
Animal a = new Animal(); //Line 1
a.saySomething(); //Line 2
Animal b = new Dog(); //Line 3
b.saySomething(); //Line 4
Dog d = new Dog(); //Line 5
d.saySomething(); //Line 6
}
}
Answer:
This code will print the following output:
I am an animal
I am an animal
I am a dog
Lines 1 and 2 create an Animal object and invoke the
saySomething method which prints “I am an Animal”. Line
3 declares an Animal variable b but
assigns it an object of type
Dog. Line 4 invokes the saySomething method using the
variable b. Normally, when a superclass
variable is assigned a
sub–class object and an overridden method is invoked, the
version from the sub–class gets executed. However,
in this case
though both the Animal and Dog classes have the
saySomething method, it is a static method.
Static methods
cannot be overridden. So, Line 4 invokes the saySomething
method from Animal class and prints I am an Animal. Lines
5 and 6 create a Dog object
and invoke the saySomething
method which prints I am a Dog.