组合的语法
将已存在类的对象放到新类中即可
- 例如说,可以说“厨房(kitchen)里有一个炉子(cooker)和一个冰箱(refrigerator)”。所以,可简单地把对象myCooker和myRefrigerator放在类Kitchen中:
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 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());
}
public double Length(){
return Math.sart(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;
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
ps:笔记整理自郑莉教授Java语言程序设计视频。