zoukankan      html  css  js  c++  java
  • 042_面向对象_15_组合

    一、继承和组合的区别

      共同点:都可以实现代码的复用
      不同点:
        is-a关系:表示是关系使用继承、如鸟是一种动物。
        has-a关系:表示拥有关系应该使用组合、如鸟类拥有翅膀。

    二、演示示例

      

    package edu.aeon.test;
    /**
     * [说明]:测试组合
     * @author aeon
     *
     */
    public class Animal {
        String eye;
    
        public void run() {
            System.out.println("跑跑!");
        }
    
        public void eat() {
            System.out.println("吃吃!");
        }
    
        public void sleep() {
            System.out.println("zzzzz");
        }
    
        public Animal() {
            super();
            System.out.println("创建一个动物!");
        }
    
        public static void main(String[] args) {
            Bird2 b = new Bird2();
            b.run();
            b.animal.eat();
        }
    }
    
    class Mammal {
        Animal animal2 = new Animal();
    
        public void taisheng() {
            System.out.println("我是胎生");
        }
    }
    
    class Bird2 {
        Animal animal = new Animal();
    
        public void run() {
            animal.run();
            System.out.println("我是一个小小小小鸟,飞呀飞不高");
        }
    
        public void eggSheng() {
            System.out.println("卵生");
        }
    
        public Bird2() {
            super();
            System.out.println("建一个鸟对象");
        }
    }

    结果截图:

      

    如有任何疑问可联系邮箱: 给我发邮件、或直接联系QQ:1584875179 || 点返回首页

  • 相关阅读:
    构建之法作业要求 20160922
    构建之法作业截止 20160908
    作业成绩 20160901
    动态范围理解
    解像力理解以及单位换算;
    QT:基本知识(一);
    qml: 截图(单窗口);
    (转载)python: getopt的使用;
    python: with的使用;
    qml: 自定义输入框
  • 原文地址:https://www.cnblogs.com/aeon/p/9967554.html
Copyright © 2011-2022 走看看