Java Reference
In-Depth Information
a constructor is called once per object creation expression. You can execute the code for one constructor only
once in the process of an object creation. If the code for a constructor is executed N times, it means N number of objects
of that class will be created and you must use N number of object creation expressions to do that. however, when an
object creation expression calls a constructor, the called constructor may call another constructor from its body. I will
cover this scenario where one constructor calls another later in this section.
Tip
Writing Code for a Constructor
So far, you have been writing trivial code in constructors. What kind of code should you write in a constructor? The
purpose of a constructor is to initialize the instance variables of the newly created object. Inside a constructor, you
should restrict yourself only to write code that initializes instance variables of the object. An object is not fully created
when a constructor is called. The object is still in the process of creation. If you write some processing logic in a
constructor assuming that a full blown object exists in memory, sometimes you may get unexpected results.
Let's create another class to represent a dog object. You will call this class SmartDog , as shown in Listing 6-30.
Listing 6-30. A SmartDog Class That Declares Two Constructors to Initialize Instance Variables Differently
// SmartDog.java
package com.jdojo.cls;
public class SmartDog {
private String name;
private double price;
public SmartDog() {
// Initialize the name to "Unknown" and the price to 0.0
this.name = "Unknown";
this.price = 0.0;
System.out.println("Using SmartDog() constructor");
}
public SmartDog(String name, double price) {
// Initialize name and price instance variables
// with the name and price parameters
this.name = name;
this.price = price;
System.out.println("Using SmartDog(String, double) constructor");
}
public void bark() {
System.out.println(name + " is barking...");
}
public void setName(String name) {
this.name = name;
}
 
 
Search WWH ::




Custom Search