Thinking in java-7 代码重用

本文探讨了面向对象编程中的代码重用方法,包括组合和继承两种方式,并详细解释了它们的应用场景及区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.代码重用的意义

Code reuse is one of the greatest advantages that object-oriented programming languages provide. Once a class has been created and tested, it should (ideally) represent a useful unit of code.
代码重用是面向对象编程所能提供的一大优势。一般而言,当我们设计好一个类后,我们可以把它作为一个有用的代码模块。

2.重用选择–组合Composition

Code reuse is one of the greatest advantages that object-oriented programming languages provide. Once a class has been created and tested, it should (ideally) represent a useful unit of code.
The simplest way to reuse a class is to just use an object of that class directly, but you can also place an object of that class inside a new class. We call this “creating a member object.”
Because you are composing a new class from existing classes, this concept is called composition (if the composition happens dynamically, it’s usually called aggregation). Composition is often referred to as a “has-a” relationship, as in “A car has an engine”.
当然最简单重用一个对象的类就是直接使用这个类的一个对象,但是我们可以将某个类的对象实例放在一个新的类中,这种方式叫做“创建一个成员对象”。
重用一般是指代一种”has-a”关系,比如“A car has an engine”.

3.重用选择–继承inheritance

We often refer to the relationship between the base class and derived class in this case as an is-a relationship, because you can say, “A circle is a shape.”
A test for inheritance is to determine whether you can state the is-a relationship about the classes and have it make sense.
首先,继承一般是一种”Is-a”关系,比如可以说”A circle is a shape”.
You have two ways to differentiate your new derived class from the original base class.
The first is quite straightforward: you simply add brand new methods to the derived class.
The second and more important way to differentiate your new class is to change the behavior of an existing base-class method. This is referred to as overriding that method.
可以通过2种主要的方式表现出继承关系来:
其一是,通过在子类中增加新的方法;
其二是,改变父类中已存在的基类方法,这就是所谓的重写overriding.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值