student student - 1 year ago 76
Java Question

JAVA class hierarchy: Which of the following lines will not compile?

Having the following class hierarchy:

Interface Animal {…}
class Dog implements Animal{…}
class Poodle extends Dog {…}
class Labrador extends Dog {…}

Which of the following lines will not compile?

Poodle poodle = new Poodle(); //1
Animal animal = (Animal) poodle; //2
Dog dog = new Labrador(); //3
animal = dog; //4
poodle = dog; //5
Animal labrador = new Labrador(); //6
Dog dog2 = new Labrador(); //7
dog 2=labrador;//8

I think line 5: because of poodle's and dog's static binding.

Line 8 : only static binding is relevant for an assignment .

Am I right? May you give an explanation?

Answer Source

You are right, statements 5 and 8 are going to fail.

5> You cannot assign a parent class' object to a child class' ref variable. A poodle is definitely a dog. But a dog may not be a Poodle.

8> Same holds true for line 8 as well. This, however, would be okay: dog2= (Dog)labrador;

Note: The explicit typecasting done in line 8 would be okay, since labrador is the object of Labrador, which is further a subclass of Dog. If you try to do the same in the case of (5), like

poodle = (Poodle)dog;

it would compile but would fail at runtime - because of the simple reason - dog refers to a Labrador. dog.getClass() would return Labrador.class. For this object to be referred by any ref, the ref should be that of a class/interface that belongs in the upward hierarchy of the object's original class. A labrador, though being a dog, is definitely not a poodle.

Also, The explicit typecasting done is Line 2 isn't very useful, since it is done implicitly. The following is where an explicit typecase would be required:

Dog d = new Labrador();
Labrador lbd = (Labrador) d;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download