组合是什么
1.继承和组合都是一种随思想渗透而下的编码方式,其根本目的都是为了复用类,减少重复代码
2.要实现一个类的复用,可以分为组合语法和继承语法
3.组合就是通过将一个对象置于一个新类中,将其作为新类的成员变量,组成 类的一部分。
4.继承和组合使用情况要随机应变
继承与组合区别
1.组合是在新类产生现有类的对象,组合出功能给更强的新类。
2.继承通过现有类的类型创建新类,并且功能在现有类的基础上进行功能上的扩展,实现更强的类。
3.继承一般在Is-A关系中(什么是什么..),组合在Has-A(什么有什么)关系。
继承语法
//1.用继承实现代码复用 package me.jicheng; class Animal{ //心脏跳动,仅供其他调用 private void beat(){ System.out.println("心脏跳动"); } //呼吸 public void breath(){ beat(); System.out.println("吸气呼气~~深呼吸~"); } } class Bird extends Animal{ //多了一个奔跑 public void fly(){ System.out.println("在你的天上自由的飞翔~~"); } } class Wolf extends Animal{ public void run(){ System.out.println("12.88冲刺啊~"); } } public class Inherit{ public static void main(String[] args){ //Bird 对象 Bird niao=new Bird(); niao.fly(); niao.breath(); //Wolf狼 Wolf lang=new Wolf(); lang.run(); lang.breath(); } }
继承语法
1.Animal实例
//2.用组合实现代码复用 package me.zuhe; class Animal{ private void beat(){ System.out.println("心脏跳动"); } public void breath(){ beat(); System.out.println("自由的呼吸"); } } class Wolf extends Animal{ //把需要的类当作实例变量加入进来实现组合 private Animal one; //构造器 public Wolf(Animal one){ this.one=one; } public void breath(){ one.breath(); } public void run(){ System.out.println("runing..."); } } class Bird{ private Animal one; public Bird(Animal one){ this.one=one; } public void breath(){ one.breath(); } public void fly(){ System.out.println("Fly..."); } } public class Composite{ public static void main(String[] args){ //创建Animal对象 Animal my=new Animal(); //创建Wolf对象并调用方法 Wolf nima=new Wolf(my); nima.run(); nima.breath(); //创建Bird对象并调用方法 Bird nimei=new Bird(my); nimei.fly(); nimei.breath(); } }
1.Car实例
//组合的方法组建汽车 package me.car; //发动机 class Engine{ public void start(){ System.out.println("引擎启动"); } //引擎加速 public void rev(){ System.out.println("引擎加速"); } public void stop(){ System.out.println("引擎停止"); } } //车轮 class Wheel{ //给轮胎打气 public void inflate(){ System.out.println("打气"); } } //车窗 class Windows{ public void rollup(){ System.out.println("看车窗爬上来~"); } public void rolldown(){ System.out.println("开往城市边缘开~我把车窗偷偷摇下来~"); } } //车门 class Door{ //车门有车窗 public Windows window=new Windows(); public void open(){ System.out.println("开车门"); } public void close(){ System.out.println("关车门"); } } class Car{ //一辆车有一个发动机,四个轮子, public Engine engine=new Engine(); public Wheel [] wheel=new Wheel[4]; public Door left=new Door(); public Door rigth=new Door(); public Car(){ for(int i=0;i<4;i++) wheel[i]=new Wheel(); } } public class TestZuhe{ public static void main(String[] args){ Car myCar=new Car(); myCar.engine.start(); myCar.engine.rev(); myCar.left.open(); myCar.rigth.window.rolldown(); } }
运行结果
yg@Gander:~/Desktop/code$ java me.car.TestZuhe 引擎启动 引擎加速 开车门 开往城市边缘开~我把车窗偷偷摇下来~
作者:YangGan
出处: http://blog.youkuaiyun.com/incyanggan
本文基于 署名 2.5 中国大陆 许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名Yanggan (包含链接).