Java Reference
In-Depth Information
Listing 6-26. A Cat Class with a Constructor
// Cat.java
package com.jdojo.cls;
public class Cat {
public Cat() {
System.out.println("Meow...");
}
}
The Cat class declares a constructor. Inside the constructor's body, it prints a message "Meow..." in the standard
output. Listing 6-27 has the code for a CatTest class, which creates two Cat objects in its main() method. Note
that you always use an object creation expression to create a new object of the Cat class. It is up to you to store the
reference of the new object in a reference variable. The first Cat object is created and its reference is not stored. The
second Cat object is created and its reference is stored in a reference variable c .
Listing 6-27. A Test Class That Creates Two of the Cat Objects
// CatTest.java
package com.jdojo.cls;
public class CatTest {
public static void main(String[] args) {
// Create a Cat object and ignore its reference
new Cat();
// Create another Cat object and store its reference in c
Cat c = new Cat();
}
}
Meow...
Meow...
Overloading a Constructor
A class can have more than one constructor. If a class has multiple constructors, they are called overloaded
constructors. Since the name of the constructor must be the same as the simple name of the class, there is a need
to differentiate one constructor from another. The rules for overloaded constructors are the same as for overloaded
methods. If a class has multiple constructors, all of them must differ from the others in the number, order, or type of
parameters. Listing 6-28 has the code for a Dog class, which declares two constructors. One constructor accepts no
parameters and another accepts a String parameter.
 
Search WWH ::




Custom Search