Initializing an Object
The new
operator instantiates a class by allocating memory for a new object and returning a reference to that memory.
The new
operator also invokes the class constructor.
This class contains a single constructor.
We can recognize a constructor because its declaration uses the same name as the class and it has no return type.
The Java compiler differentiates the constructors based on the number and the type of the arguments.
The constructor in the
Dog
class takes four arguments.
The following statement provides “tuffy,” “pointer,” 5, and “white” as values for those arguments:
Dog tuffy = new Dog( "tuffy", "pointer", 5, "white" );
Note that all classes have at least one constructor.
If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the
default constructor.
This default constructor calls the class parent’s no-argument constructor (as it contain only one statement; i.e.,
super();
), or the
Object
class constructor if the class has no other parent (as
Object
class is parent of all classes either directly or indirectly).