一.概念
在新类中简单创建原有类的对象,即一个类的对象是另外一个类中的成员。其操作方法是将已经存在类的对象放到新类中即可。
例:厨房(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