Java polymorphism creating a subclass object using its superclass variable

前端 未结 3 1844
猫巷女王i
猫巷女王i 2021-01-02 09:48

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 t

相关标签:
3条回答
  • 2021-01-02 10:03
    1. Any overridden methods in the Lizard class will be used instead of those in the Animal class

      Yes, you're right

    2. which classes constructor will be used while creating a?

      When you create a subclass, it will implicitly call super class's constructor. Hence, both super class, which is Animal, and sub class, which is Lizard, will be used.

    0 讨论(0)
  • 2021-01-02 10:08

    1.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>

    yes, you are Right.

    2.Also, which classes constructor will be used while creating a?

              Animal a = new Lizard("Lizzy", 6);  //Lizard extends Animal
    

    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's constructor will be invoked as java.lang.Object is the super class of every object.

      public Object() {
    
        }
        Class Animal {
         public Animal(){
          //there will be a super call here like super()
        }
    
        class lizard extends Animal {
        public Lizard(your args) {
           //there will be a super() call here and this call's animal's no-args constructor
         }
        }
    
     }
    

    The order of execution would be

    1. Lizards constructor will be invoked
    2. unless there is a this() call to an overloaded constructor, a call to super() i.e., call's Animals no-args Constructor
    3. java.lang.Object's Constructor will be invoked from animal using super()
    4. java.lang.Object's constructor code will execute
    5. Animals constructor code will execute
    6. Lizards constructor code will execute
    0 讨论(0)
  • 2021-01-02 10:15
    1. This is correct, even though the reference is of type Animal, all method calls will resolve to the definition in Lizard if present, otherwise the version in the next immediate parent will be called and so on.

    2. a is just a reference and the actual object is of type Lizard. So, the constructors in Lizard class will be called. They in turn can call the constructors in super classes using super().

    0 讨论(0)
提交回复
热议问题