您的位置:首页 > 编程语言 > Java开发

thinking in java 学习笔记之Composition vs Inheritance

2005-08-25 20:39 1011 查看
1. Composition:
    通过在类中直接使用另一个类的对象来达到重用代码的目的。
    Composition通常用在:当你想在你的新类中使用已有类的功能,而不是使用已有类的接口时。
    这时,你可以在你的新类中嵌入已有类的对象,来完成你想要的功能。
    Composition通常表述为“has a ”的关系,比如一样东西由一系列组件构成(车有轮胎、窗子、发动机。。。)
2. Inheritance:
    Inheritance通常表述为“is a ”的关系.比如car is a type a vehicle.
    继承要表达的关系是:"This new class is type of that old class".
3. Upcasting
    (1)upcasting:把子类的引用传递给父类,当作父类的引用来使用。
    因为通过继承,父类中所有的方法在子类中都是可用的(private除外),即任何传递给父类的消息都能传递给子类。
    例子:
    //Inheritance and Upcasting-------------------------
    class Instrument{
 public void play(){}
 static void tune(Instrument i){
     //....
     i.play();
 }
    }
    public class Wind extends Instrument{
 public static void main(String[] a){
     Wind wind = new Wind();
            Instrument.tune(wind);//Upcasting
 }
    }
    //---------------------------------------------------
    这样,在调用的时候可以“忘记”子类的类型,直接通过“父类.方法名(子类的引用)”来调用父类的方法“方法名(父类的引用)”,从而将子类的引用传递给父类的引用,实现某个子类需要完成的功能。
    (2)Upcasting总是安全的。
    因为你是把一个更具体的类型转换成一个抽象的类型。这就是说子类是父类的超集。子类可能包含了比父类更多的方法,但是他至少必须包含父类中的所有方法。
    upcast时唯一发生的事是:方法的丢失,即功能的缩减。
4. How to choose Inheritance and Composition?
    关键看是否需要Upcasting.
    One of the clearest ways to determine whether you should use composition or inheritance is to ask whether you'll ever need to upcast from your new class to base class? If you must upcast,then inheritance is necessary.
   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息