0

Does it happen to initialize instance variables? But does no-arg constructor initialize instance fields?
Sample code:-

class GenericAnimal{
    private String name;
    GenericAnimal(){
        System.out.println("parent constuctor");
    }
}
public class PolymorphismTest extends GenericAnimal {

    PolymorphismTest(){
        System.out.println("child constructor");
    }
    public static void main(String[] args) {
        new PolymorphismTest(); //creating an object of child class
    }

}

output:-
parent constuctor
child constructor

Sandeep D
  • 157
  • 7
  • 2
    "Does it happen to initialize instance variables?" yes, that is quite a good reason. – Pshemo Aug 08 '15 at 19:36
  • 2
    What did you think was the alternative? How would the field in the parent get initialised without calling a constructor? – Peter Lawrey Aug 08 '15 at 19:39
  • @PeterLawrey A setter method perhaps? Please excuse my ignorance if I sound stupid. – Sandeep D Aug 08 '15 at 19:54
  • Does a no-arg constructor initialize instance variables in some way? If it doesn't, what's the point of invoking it while creating a child object? – Sandeep D Aug 08 '15 at 20:13
  • When object is created, its fields are set to default values (`0`, `0.0`, `'\0'`, `false` or for references `null`). To ensure objects won't stay in that default state code of constructor is being called. In other words purpose of constructors is to guarantee that objects will be initialized properly, in a way class was *designed*. So if we are extending some class, we need to let it initialize its fields to originally designed state, and then set it up to our design. Easiest way to do it is by calling constructor of superclass before executing code in our constructor. – Pshemo Aug 08 '15 at 23:07
  • @Pshemo Thanks man. **When object is created, its fields are set to default values (0, 0.0, '\0', false or for references null).** <-- This cleared my doubt. – Sandeep D Aug 09 '15 at 07:56

0 Answers0