Writing Constructors
Writing Constructors
Understanding Constructors
- A constructor is a special method in a class that is used to initialise new objects of that class.
- Unlike normal methods, constructors do not have a return type and their name must exactly match the name of the class.
- If a class does not have a declared constructor, Java will provide a default one for you. This default constructor has no parameters, and doesn’t do anything besides creating a new instance of the class.
- You can create your own constructors with any number of parameters. This allows you to set some initial state for your objects.
Writing Constructors
- When writing a constructor, it should typically start with a call to
super()
, the constructor of the superclass. This ensures that the object is set up correctly according to the superclass’s rules. - If
super()
is not explicitly called, Java will insert a call to the no-argument constructorsuper()
at the start of the constructor for you. - You can use
this
keyword to call a different constructor within the same class. - When writing a constructor for a subclass, if
super()
is used, it must be the first statement in the constructor.
Overloading Constructors
- Overloading constructors means providing more than one constructor in a class, each with a different parameter list.
- When an object is initialised, Java will choose the correct constructor to use by matching the arguments provided with the parameter list of each constructor.
- If no matching constructor is found, Java will give a compile-time error.
- Overloading constructors can provide flexibility in how an object can be initialised, making the code more user-friendly.
Inheritance and Constructors
- Subclasses inherit all the fields and methods from their superclass, but they do not inherit constructors.
- This is because constructors are not considered “members” of a class.
- However, the constructor of a subclass may call a constructor from the superclass using the
super()
keyword. - When a subclass object is created, the constructor of the superclass (specified by
super()
) will be called first, then the constructor of the subclass.
Default Constructors and Inheritance
- If a base class has a constructor that takes parameters and no no-parameter constructor, any subclasses must explicitly call the base class constructor using
super()
, passing the appropriate parameters. - If this is not done, Java will attempt to call the nonexistent no-parameter constructor in the base class when constructing a subclass object, which will cause a compile-time error.