|
|
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
The Circle class has 2 constructors defined:
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/03-classes/05-rules-constr
The Circle class now has 1 constructor defined:
public class Circle { double radius = 1; /** The radius of this circle */ Circle(double newRadius) /** Constructor 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/03-classes/05-rules-constr (delete Circle())
The Circle class now has no constructors defined:
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/03-classes/05-rules-constr (delete Circle(double))