在這裏,您是如何可以做一個例子:
超類(Point2D.java):
package test_superArg;
public class Point2D {
private float x;
private float y;
public Point2D(float x, float y) {
this.x = x;
this.y = y;
System.out.println("Parent class constructor:");
System.out.println("X = " + this.x + ", Y = " + this.y);
}
public float getX() {return x;}
public float getY() {return y;}
public void setX(float x) {this.x = x;}
public void setY(float y) {this.y = y;}
}
子類(Point3D.java):
package test_superArg;
public class Point3D extends Point2D {
private float z;
public Point3D(Point2D point2d, float z) {
super(point2d.getX(), point2d.getY()); // must be the 1st statement in a constructor
System.out.println("After calling super()");
this.z = z;
System.out.println("Child class constructor:");
System.out.println("X = " + getX() + ", Y = " + getY() + ", Z = " + this.z);
}
public float getZ() {return z;}
}
主類(Start.java):
package test_superArg;
public class Start {
public static void main(String[] args) {
System.out.println("Creating parent type class object...");
Point2D point2d = new Point2D(2.0f, 4.0f);
System.out.println("Creating child type class object...");
Point3D point3d = new Point3D(point2d, 8.0f);
System.out.println("Changing child class type object...");
point3d.setX(10.0f);
point3d.setY(20.0f);
System.out.println("Parent type class object:");
System.out.println("X = " + point2d.getX() + ", Y = " + point2d.getY());
System.out.println("Child type class object:");
System.out.print("X = " + point3d.getX() + ", Y = " + point3d.getY());
System.out.println(", Z = " + point3d.getZ());
}
}
輸出:
Creating parent type class object...
Parent class constructor:
X = 2.0, Y = 4.0
Creating child type class object...
Parent class constructor:
X = 2.0, Y = 4.0
After calling super()
Child class constructor:
X = 2.0, Y = 4.0, Z = 8.0
Changing child class type object...
Parent type class object:
X = 2.0, Y = 4.0
Child type class object:
X = 10.0, Y = 20.0, Z = 8.0
什麼是用例? – Bohemian 2012-02-05 09:42:39