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)”的关系

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

  • 相关阅读:
    Vue3教程:Vue3.0 + Vant3.0 搭建种子项目
    硬盘
    org.apache.commons.beanutils.ConversionException: No value specified
    软件设计流程
    CDN使用
    The valid characters are defined in RFC 7230 and RFC 3986
    java.lang.IllegalArgumentException: More than one fragment with the name [spring_web] was found.
    joomla安装
    LAMP环境
    开源软件
  • 原文地址:https://www.cnblogs.com/baby-zhude/p/8045143.html
Copyright © 2011-2022 走看看