|
|
Just like regular methods,
constructors
can be
overloaded
(I.e.,
multiple
constructors can be
defined
with
different
signatures)
public class Circle
{
public double radius = 1; /** The radius of this circle */
public Circle() { } /** Called when you use: new Circle() */
public Circle(double newRadius) /** Called when you use: new Circle(num) */
{
radius = newRadius;
}
public double getArea() /** Return the area of this circle */
{
return 3.14159 * radius * radius;
}
public void setRadius(double newRadius) /** Set new radius for this circle */
{
radius = newRadius;
}
}
|
|
I will show you examples to illustrate the rules next
Consider a Circle class that contains 2 constructors:
public class Circle
{
double radius = 1; /** The radius of this circle */
Circle() { } /** Constructor 1 for a circle object */
Circle(double newRadius) /** Constructor 2 for a circle object */
{
radius = newRadius;
}
}
|
The Circle class has at least 1 constructor, so the Java compiler will not insert the default constructor
DEMO: demo/10-classes/05-rules-constr/Circle.java + Demo.java -- Compile with no error
Suppose we delete the constructor Circle( ):
public class Circle
{
double radius = 1; /** The radius of this circle */
Circle(double newRadius) /** Constructor for a circle object */
{
radius = newRadius;
}
}
|
Again, the Circle class has at least 1 constructor, the Java compiler will not insert the default constructor
DEMO: demo/10-classes/05-rules-constr -- delete Circle( ) and show compile error
Suppose we delete both constructors:
public class Circle
{
double radius = 1; /** The radius of this circle */
}
|
The Circle class has no constructors, so the Java compiler will insert the default constructor
DEMO: demo/10-classes/05-rules-constr (delete Circle(double))