一.类的组合:选用已有类的对象作为,表达的是有一个的包含关系
思想:程序中的部件由对象组装而成它的成员
栗子:线段类
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 int 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());
}
}
二.继承与组合
1.继承:是一个、是一种,这样的从属关系
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 //声明器具
{
public 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 //餐桌的布置,继承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(5);
}
}
//运行结果:
// Custom constructor
// Utensil constructor
// Spoon constructor
// Utensil constructor
// Fork constructor
// Utensil constructor
// Knife constructor
// Plate constructor
// DinnerPlate constructor
// PlaceSetting constructor