一.概念
在新類中簡單創建原有類的對象,即一個類的對象是另外一個類中的成員。其操作方法是將已經存在類的對象放到新類中即可。
例:廚房(Kitchen)中有爐子(cooker)和冰箱(refrigerator)。
class Cooker{//類的語句} class Refrigerator{//類的語句} class Kitchen{ Cooker myCooker; Refrigerator myRefrigerator; }
例:線段類--一個線段類包含兩個端點。
public class Point //點類 { private int x,y; public Point(int x,int y) { this.x = x; this.y = y; } public int GetX() { return x; } public inr GetY() { return y; } } class Line { private Point p1,p2; Line(Point a,Point b) { p1 = new Point(a.GetX(),a.GetY()); p2 = new Point(b.GetX(),b.GetY()); } public double Length() { return Math.sqrt(Math.pow(p2.GetX() - p1.GetX(),2) + Math.pow(p2.GetY() - p1.GetY(),2)); } }
二.組合與繼承的結合
class Plate{//聲明盤子 public Plate(int i){ System.out.println("Plate constructor"); } } class DinnerPlate extends Plate{//聲明餐盤為盤子的子類 public DinnerPlate(int i){ super(i); System.out.println("DinnerPlate constructor"); } } class Utensil{//聲明器具 Utensil(int i){ System.out.println("Utensil constructor"); } } class Spoon extends Utensil{//聲明勺子為器具的子類 public Spoon(int i){ super(i); System.out.println("Spoon constructor"); } } class Fork extends Utensil{//聲明叉子為器具的子類 public Fork(int i){ super(i); System.out.println("Fork constructor"); } } class Knife extends Utensil{//聲明餐刀為器具的子類 public Knife(int i){ super(i); System.out.println("Knife constructor"); } } class Custom{ public Custom(int i){ System.out.println("Custom constructor"); } } public class PlaceSetting extends Custom{ Spoon sp;Fork frk;Knife kn; DinnerPlate pl; public PlaceSetting(int i){ super(i+1); sp = new Spoon(i+2); frk = new Fork(i+3); kn = new knife(i+4); pl = new DinnerPlate(i+5); System.out.println("PlaceSetting constructor"); } public static void main(String[] args){ PlaceSetting x = new PlaceSetting(9); } } //運行結果 Custom constructor Utensil constructor Spoon constructor Utensil constructor Fork constructor Utensil constructor Knife constructor Plate constructor DinnerPlate constructor PlaceSetting constructor