Java Reference
In-Depth Information
Listing 6-28. A Dog Class with Two Constructors, One with No Parameter and One with a String Parameter
// Dog.java
package com.jdojo.cls;
public class Dog {
// Constructor #1
public Dog() {
System.out.println("A dog is created.");
}
// Constructor #2
public Dog(String name) {
System.out.println("A dog named " + name + " is created.");
}
}
If a class declares multiple constructors, you can use any of them to create an object of that class. For example,
the following two statements create two objects of the Dog class:
Dog dog1 = new Dog();
Dog dog2 = new Dog("Cupid");
The first statement uses the constructor with no parameters and the second one uses the constructor with a
String parameter. If you use a constructor with parameters to create an object, the actual parameter's order, type and
number must match the formal parameter's order, type and number. Listing 6-29 has the complete code that creates
two Dog objects using different constructors.
Listing 6-29. Testing the Constructors of the Dog Class
// DogTest.java
package com.jdojo.cls;
public class DogTest {
public static void main(String[] args) {
Dog d1 = new Dog(); // Uses Constructor #1
Dog d2 = new Dog ("Canis"); // Uses Constructor #2
}
}
A dog is created.
A dog named Canis is created.
The output of running the DogTest class indicates that different constructors are called when two Dog objects are
created in the main() method.
Search WWH ::




Custom Search