Page 301 - Introduction to Programming with Java: A Problem Solving Approach
P. 301

                Figure 7.13
Car4 class, which has a constructor
Accommodating Java’s Fickle Default Constructor
Any time you instantiate an object (with new), there must be a matching constructor. That is, the number and types of arguments in your constructor call must match the number and types of parameters in a defined constructor. But until recently, we’ve instantiated objects without any explicit constructor. So were those examples wrong? No. They all used a zero-parameter freebie default constructor that the Java compiler automatically provides if and only if there is no explicitly defined constructor. The Employee program in Figures 7.15a and 7.15b illustrates the use of Java’s implicit zero-parameter default constructor.
InFigure7.15a,notehowmain’snew Employee()codecallsazero-parameterconstructor.But Figure 7.15b does not define a zero-parameter constructor. No problem. Since there are no other construc- tors, the Java compiler provides the default zero-parameter constructor, and it matches up with the new Employee() zero-argument constructor call.
Note that as soon as you define any kind of constructor for a class, Java’s default constructor becomes un- available. So if your class contains an explicit constructor definition, and if main includes a zero-argument constructor call, you must also include an explicit zero-parameter constructor in your class definition.
7.8 Constructors 267
 /**************************************************
*
Car4.java
Dean & Dean
This class stores and retrieves data for a car.
**************************************************/
*
*
*
public class Car4
{
private String make;
// car's make
// car's manufacturing year
private String color; // car's primary color
private int year;
//***********************************************
public Car4(String m, int y, String c) ⎫ {⎪
  }
// end class Car4
this.make = m;
⎪ ⎬
 this.year = y; ⎪
this.color = c; ⎪ } // end constructor ⎭
//***********************************************
       Apago PDF Enhancer
public String getMake()
{
return this.make;
} // end getMake
constructor definition





























































   299   300   301   302   303