Java类的组合与继承的关系你了解多少?

类的组合

组合的意义

  • 面向对象的程序用软件对象来模仿现实世界的对象:
    • 现实世界中,大多数对象由更小的对象组成;
    • 与现实世界的对象一样,软件中的对象也常常是由更小的对象组成。
  • Java的类中可以有其他类的对象作为成员,这便是类的组合。
  • 组合也是一种重用机制,可以使用“有一个” 来描述这种关系。

组合的语法

  • 将已存在类的对象放到新类中即可
  • 例如,可以说“厨房( kitchen)里有一个炉子(cooker)和一个冰箱(refrigerator)”。所以,可简单的把对象myCooker和myRefrigerator放在类Kitchen中:
class Cooker{   // 类的语句 }
class Refrigerator{   // 类的语句}
class Kitchen{   
Cooker myCooker;
Refrigerator myRefrigerator;
}

组合举例:线段类

  • 一条线段包含两个端点

    public class Point   //点类
    {
    	private int x, y;  //coordinate
    	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.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
发布了9 篇原创文章 · 获赞 4 · 访问量 262

猜你喜欢

转载自blog.csdn.net/weixin_43414889/article/details/105660732
今日推荐