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.
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).
We get used to that, we endure, we harden, we batten down the hatches (prepare for the trouble) to protect our habits. |