类的组合

组合的语法

将已存在类的对象放到新类中即可

  • 例如说,可以说“厨房(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语言程序设计视频。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值