除了继承,组合也能实现代码的复用。组合的核心是将对象作为子类的属性;
package com.it.test;
public class Test {
public static void main(String[] args) {
Student s = new Student("小明", 20, "Java");
s.person.rest();
s.study();
}
}
class Person {
String name;
int height;
public void rest() {
System.out.println("休息一下");
}
}
class Student /*extends Person*/ {
Person person = new Person();
String magor;
public Student(String name, int height, String magor) {
this.person.name = name;
this.person.height = height;
this.magor = magor;
}
public void study() {
System.out.println("学习一会");
}
}
组合比较灵活,继承只能有一个父类,但是组合可以有多个属性。
对于is - a 建议走继承。对于has - a 建议走组合;
例如上述例子:Student is a Person 则走继承;Student has a Person 就有问题了;这时候显然继承更合适;
更比如:笔记本 和 芯片更合适用 has - a 组合的关系;