Inherit_Composition

  • The "is-a" relationship uses inheritance!
    1. The above code is reused by adding a Car attribute to the Audi class, but the logic is not easy to understand.

  • The "has-a" relationship uses composition!
    1. Computer class, motherboard class. You can reuse the code of the motherboard class by adding the motherboard attribute in the computer class!

package theChildOfGod.bjxy.oop.inherit;
/*
 * 测试组合
 * 
 */
public class Animal2{
    String eye;

    public void run() {
        System.out.println("跑跑!");
    }
    public void eat() {
        System.out.println("吃吃!");
    }
    public void sleep() {
        System.out.println("zzzzzz");
    }
    public Animal2() {
        super();
        System.out.println("创建一个动物!");
    }
    public static void main(String[] args) {
        Bird2 b = new Bird2();
        b.run();
        b.animal2.eat();

        Mammal2 c = new Mammal2();
        c.taisheng();
    }
}
class Mammal2 {
    Animal2 animal2 = new Animal2();
    public void taisheng() {
        animal2.sleep();
        System.out.println("我是胎生");
    }
}
class Bird2 { 
    Animal2 animal2 = new Animal2();
    public void run(){
        animal2.run();
        System.out.println("我是一只小小鸟!飞呀飞不高!");
    }
    public void eggSheng() {
        System.out.println("卵生");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324516402&siteId=291194637