Constructors and Initialization
Explore how Java creates and initializes objects through constructors, static and instance blocks, and inheritance. Understand the execution order and best practices to avoid setup bugs.
We'll cover the following...
Once a class is defined and its access boundaries are set, we need a way to bring its objects to life. Object creation in Java is a highly structured process that involves allocating memory, setting default values, and executing developer-defined setup logic. At the heart of this process is the constructor.
Let's explore what happens when we create an object and how Java handles classes that do not explicitly define their setup routines.
What happens if a class does not explicitly define a constructor?
Can a class in Java have a static constructor to initialize static fields?
Question
Consider the following parent and child classes. What is missing in the code below?
public class ParentClass {
protected int counter;
public ParentClass(int val) {
this.counter = val;
}
}
public class EmptyChildClass extends ParentClass {
public EmptyChildClass() {
}
}
The code will not compile because the parent class doesn’t define a no-argument default constructor.
The child class cannot inherit a protected variable.
The child class must override the parent’s constructor.
In Java, the child constructor implicitly tries to call ...