So I am a student and in the process of learning Java. There is one concept that I am having a difficult time grasping and am hoping that someone could shed some light on this for me. My question is regarding polymorphism. Let’s say for example I have the following code.
Animal a = new Lizard("Lizzy", 6); //Lizard extends Animal
-
From what I understand, since the variable type is Animal, a will have all the characteristics of an Animal. But, since the object created is a Lizard, any overridden methods in the Lizard class will be used instead of those in the Animal class. Is this correct>
-
Also, which classes constructor will be used while creating a?
Thanks for any help. I have looked quite
yes, you are Right.
As, Lizard is a subclass of Animal, First, Lizards constructor will be invoked, then from Lizards constructor, there will be a call to Animal constructor as the first line in your Lizard constructor would be super() by default unless you call an overloaded constructor of Lizard using this(). In Animal constructor there will be another call to super() in the first line. assuming Animal doesn’t extend any class,
java.lang.Object'sconstructor will be invoked asjava.lang.Objectis the super class of every object.The order of execution would be