[Java 教學範例拷貝]- 擴充(extends)父類別(2/2)
[Java 教學範例拷貝]- 擴充(extends)父類別(2/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() {x = 0; y = 0;}
public Point2D(int x, int y) {this.x = x; this.y = y;}
public int getX() {return x;}
public int getY() {return y;}
public void setX(int x) {this.x = x;}
public void setY(int y) {this.y = y;}
}
|
public class Point3D extends Point2D { // 繼承Point2D類別
private int z; // 新增私用資料
public Point3D() {
z = 0;
}
// 建構函式,同時指定呼叫父類別建構函式
Point3D(int x, int y, int z) {
super(x, y);
this.z = z;
}
// 新增函式
public int getZ() {return z;};
public void setZ(int z) {this.z = 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());
p2.setX(2);
p2.setY(4);
p2.setZ(6);
System.out.printf("p2: (%d, %d, %d) \n",
p2.getX(), p2.getY(), p2.getZ());
}
}
|