java中composition_thinking in java 学习笔记之Composition vs Inheritance | 学步园

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值