zoukankan      html  css  js  c++  java
  • 继承与组合:

    如下代码,三个类,体会继承(inherit)与组合(composite)的魅力所在:

    继承:

    package Inherit;
    import static java.lang.System.*;
    class Animal{
    	private void beat(){
    		out.println("生命在于心脏跳动!");
    	}
    
    	public void breath(){
    		beat();
    		out.println("生命在于呼吸之间!");
    	}
    }
    
    class Birds extends Animal{
    	public void fly(){
    		out.println("生命在于自由飞翔!");
    	}
    }
    
    class Wolf extends Animal{
    	public void run(){
    		out.println("生命在于自由奔跑!");
    	}
    }
    
    public class InheritTest{
    	public static void main(String[] args){
    		Birds b=new Birds();
    		b.breath();
    		b.fly();
    
    		Wolf w=new Wolf();
    		w.breath();
    		w.run();
    	}
    }
    

    运行结果:

    组合:

    package Composite;
    import static java.lang.System.*;
    class Animal{
    	private void beat(){
    		out.println("生命在于心脏跳动!");
    	}
    	
    	public void breath(){
    		beat();
    		out.println("生命在于呼吸之间!");
    	}
    }
    
    class Birds{
    	private Animal a;
    	public Birds(Animal a){
    		this.a=a;
    	}
    	
    	public void breath(){
    		//-直接复用Animal类breath()方法来实现Birds类的breath()方法;
    		a.breath();
    	}
    	
    	public void fly(){
    		out.println("生命在于自由飞翔!");
    	}
    }
    
    class Wolf{
    	private Animal a;
    	public Wolf(Animal a){
    		this.a=a;
    	}
    	
    	public void breath(){
    		//-直接复用Animal类breath()方法来实现Wolf类的breath()方法;
    		a.breath();
    	}
    	
    	public void run(){
    		out.println("生命在于自由奔跑!");
    	}
    }
    
    public class CompositeTest{
    	public static void main(String[] args){
    		Animal a=new Animal();
    
    		Birds b=new Birds(a);
    		b.breath();
    		b.fly();
    
    		Wolf w=new Wolf(a);
    		w.breath();
    		w.run();
    	}
    }
    

    运行结果:

    总结:

    1、继承,是实现类复用的重要手段,但带来了最大的一个坏处:破坏封装

    2、组合,也是实现类复用的重要方式,而且能提供更好的封装性

    何时用继承?组合?

    1、继承:对已有的类做一番改造,以此获得一个特殊的版本,继承表达的是一种“是(is-a)”的关系

    2、组合:两个类之间有明确的整体、部分的关系,组合表达的是一种“有(has-a)”的关系

    不管是用继承还是组合,对系统的开销来说没有本质的区别!!!

  • 相关阅读:
    二、魔法函数
    Metaclasses
    一、python中的一切皆对象
    三、鸭子类型
    SQL进行排序、分组、统计的10个新技巧
    输入地址栏可以编辑页面的js
    项目开发中常用JS表单取值方法
    [导入]通用的分页存储过程
    107个常用Javascript语句
    [导入]事务处理
  • 原文地址:https://www.cnblogs.com/baby-zhude/p/8045143.html
Copyright © 2011-2022 走看看