| |
The syntax for a constructor is as follows. | |
| |
|
public class MainClass {
double radius;
MainClass() {
}
// Class constructor
MainClass(double theRadius) {
radius = theRadius;
}
}
Multiple Constructors
class Sphere {
int radius = 0;
Sphere() {
radius = 1;
}
Sphere(int radius) {
this.radius = radius;
}
}
Calling a Constructor From a Constructor
class Sphere {
int radius = 0;
double xCenter;
double yCenter;
double zCenter;
Sphere() {
radius = 1;
}
Sphere(double x, double y, double z) {
this();
xCenter = x;
yCenter = y;
zCenter = z;
}
Sphere(int theRadius, double x, double y, double z) {
this(x, y, z);
radius = theRadius;
}
}
Duplicating Objects using a Constructor
class Sphere {
int radius = 0;
double xCenter;
double yCenter;
double zCenter;
Sphere() {
radius = 1;
}
Sphere(double x, double y, double z) {
this();
xCenter = x;
yCenter = y;
zCenter = z;
}
Sphere(int theRadius, double x, double y, double z) {
this(x, y, z);
radius = theRadius;
}
// Create a sphere from an existing object
Sphere(final Sphere oldSphere) {
radius = oldSphere.radius;
xCenter = oldSphere.xCenter;
yCenter = oldSphere.yCenter;
zCenter = oldSphere.yCenter;
}
}
Class Initializer: during declaration
// ClassInitializer2.java
class ClassInitializer2 {
static boolean bool = true;
static byte by = 20;
static char ch = 'X';
static double d = 8.95;
static float f = 2.1f;
static int i = 63;
static long l = 2L;
static short sh = 200;
static String str = "test";
public static void main(String[] args) {
System.out.println("bool = " + bool);
System.out.println("by = " + by);
System.out.println("ch = " + ch);
System.out.println("d = " + d);
System.out.println("f = " + f);
System.out.println("i = " + i);
System.out.println("l = " + l);
System.out.println("sh = " + sh);
System.out.println("str = " + str);
}
}
Order of constructor calls
class Meal {
Meal() {
System.out.println("Meal()");
}
}
class Bread {
Bread() {
System.out.println("Bread()");
}
}
class Cheese {
Cheese() {
System.out.println("Cheese()");
}
}
class Lettuce {
Lettuce() {
System.out.println("Lettuce()");
}
}
class Lunch extends Meal {
Lunch() {
System.out.println("Lunch()");
}
}
class PortableLunch extends Lunch {
PortableLunch() {
System.out.println("PortableLunch()");
}
}
class Sandwich extends PortableLunch {
private Bread b = new Bread();
private Cheese c = new Cheese();
private Lettuce l = new Lettuce();
public Sandwich() {
System.out.println("Sandwich()");
}
}
public class MainClass {
public static void main(String[] args) {
new Sandwich();
}
}
Meal() Lunch() PortableLunch() Bread() Cheese() Lettuce() Sandwich()
http://www.java2s.com/Tutorial/Java/0100__
Class-Definition/Catalog0100__Class-Definition.htm
No comments:
Post a Comment