[Java 教學範例拷貝]- 擴充(extends)父類別
[Java 教學範例拷貝]- 擴充(extends)父類別(1/2)
剛才找資料時發現一個的Java 教學網站,趕快發揮(C/P)的長才將它備份來,有需要的同好,歡迎來(C/P)一下^^。
拷貝來源:
http://openhome.cc/Gossip/JavaGossip-V1/
http://openhome.cc/Gossip/JavaGossip-V1/ExtendParentClass.htm
public class Point2D {
private int x, y;
public Point2D() {}
public Point2D(int x, int y) {this.x = x; this.y = y;}
public int getX() {return x;}
public int getY() {return y;}
}
|
public class Point3D extends Point2D { // 擴充Point2D類別
private int z; // 新增私用資料
public Point3D() {
super();
}
// 建構函式,同時指定呼叫父類別建構函式
Point3D(int x, int y, int z) {
super(x, y);
this.z = z;
}
// 新增函式
public int getZ() {return z;}
}
|
public class UseExtend {
public static void main(String[] args) {
Point3D p1 = new Point3D(1, 3, 4);
Point3D p2 = new Point3D();
System.out.printf("p1: (%d, %d, %d) \n",
p1.getX(), p1.getY(), p1.getZ());
System.out.printf("p2: (%d, %d, %d) \n",
p2.getX(), p2.getY(), p2.getZ());
}
}
|