版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
继承多态继承vs组合继承和构造方法Outline继承A
Case
for
Inheritance5.
Finish
the
class
hierarchyFeline
class
and
Canine
classFelines
could
use
a
common
roam().Whiethod is
called?When
one
class
inherits
from
another,
wesay
that
the
subclass
extends
the
superclass.When
you
want
to
know
if
one
thing
shouldextend
another,
apply
the
IS-A
test.Using
IS-A
and
HAS-AHAS-ATransitive
LawWhen designing
with
inheritanceIs-ais-like-ais-a
vs
is-like-aA:
One
of
the
key
benefits
of
inheritance
isto
minimise
the
amount
of
duplicate
code
inan
application
by
sharing
common
codeamongst
several
subclasses.Inheritance
c so
make
application
codemore
flexible
to change
because
classes
thatinherit
from a
common superclass
can
beused
interchangeably.Q:
What
are
the
benefits
of
inheritance?Q:What
forms
of
inheritance
are
supported
byJava?
A:The
standard
form
of
inheritance
is
byextensionThe
second
special
form
of
inheritance
iswhere classes
declare
that
they
implement
aninterface,
which
hasmore
limitedconsequences.A:
An
example
of
inheritance
using
the
extends
keywordwould
be
the
java.util.Stack
class
that
extends
the
Vectorclass
to
provide
a
last-in-
-out
stack
of
Objects.The
Stack
class
uses
the
same
underlying
storage
facilitiesprovided
by
the
superclass
and
adds
its
own,
so
it
"is
a"type
of
Vector and
behaves
like
a
specialised
"wrapper"around
the
Vector
class.The
Stack
class
adds
a
boolean
empty()
method,
peek(),pop()
and
push()
methods
to manage
the
stack
contentsand
a
search()
method
to
find
the
index
of
a
given
object.All
the
original
methods
of
the
Vector
class
remain
andthe
Stack
can
be
cast
to a
Vector
as
necessary.Q:
Can
you
show
examples
of
Java
inheritance?Benefits
of
inheritance多态Wolf
aWolf
=
new
Wolf();Animal
aHippo
=
new
Hippo();It is
weird:Animal
anim
=
new
Animal();A
weird
phenomenonThe
new
hierarchymethodsN
oMethod
in
a
Non-Class
methods
exist
solely
forpolymorphism.A
concrete
class
must
implement
allmethods.Implementing
an
method is
just
likeoverriding
a
method.Implement
methodsBuilding
the
Dog-specific
list动物的Arraylist每个动物对象表现下他们的行为•新的一种动物加入进来If
we
need
to
keep
Cats?Make
a
separate
class
MyCatList?Make
an
animal
list
to
take
any
kind
of
animals.问题•We
don’t
have
a
superclass
for
Animal?Every
class
in
Java
extends
classObject,
without
you
ever
having
tosay
it.You
can
think
of
it
as
though
a
class
youwri
ooks
like:Public
class
Dog
extends
Object
{}•The
compiler
decideswhether
you
cancalla
method
based
on
the
referencetype,
not
theactual
object
type.The
compiler
checks
the
class
of
the
reference
type–
not
the
object
type
–
to see
if
you
can
call
amethod using
that
reference.The
JVM
decides
which
actual
methodis
called
based
on
the
actual
objecttype.•An
object
contains
everything
it
inheritsfrom each
of
its
superclasses.That
means
every
object
–
regardless
of
itsactual
class
type
–
is
also
an
instance
of
classObject.Inner
ObjectDog
example•••多态通过分离“
做什么”
和“
怎么做”,从另一角度将接口
分离开来。多态不但能够改善代码的组织结构和可读性,还能够创建“可扩展的”程序,即无论在项目最初创建时,还是在需要添加新功能时,都可以进行扩充。更容易理解。而多态的作用则是消除类型之间的耦合关系多态方法调用允许一种类型
与其他相似类型之间的区别,只要它们都是从同一基类导出而来的。这种区别是根据方法行为的不同来而表示出来的,虽然这些方法都可以通过同一个基类来调用。多态的意思是“多种形式”,多种形式的意思是可以出现不同的计算类型,并且在运行的时候动态的确定正确的计算。多态是指多个方法使用同一个名字有多种解释,当使用这个名字去调用方法时,系统将选择重载自动的选择其中的一个方法。在多态中只关心一个对象做什么,而不关心如何去做。多态的思想The
Same
TypeN
o
t
The
Same
Type类型检查必须按照方法形参的类型来检查消息的参数类型,必须按消息所期待的类型来检查方法的返回类型。绑定绑定在程序中的意思是把一个标志符与一个单元或者把一个标志符与一个变量,方法建立起联系。动态绑定在运行时,根据对象的类型进行绑定。类型检查和动态绑定Polymorphism
--
Reference
TypePolymorphism
–
Arguments and
ReturnTypeReuse••“
多态”
意味着“
不同的形式”
。在面 象的程序设计中,我们持有相同的外观(基类的通用接口)以及使用该外观的不同形式:不同版本的动态绑定方法。如果不运用数据抽象和继承,就不可能去理解,进而也不可能创建一个多态例子。多态是一种不能单独来看待的特性(例如,像switch
语句是可以的),相反它只能作为类关系“全景”中的一部分,与其它特性协同工作。人们经常被Java语言中其他的非面
象的特性所困扰,比如方法重载等,人们有时会被认为这些是面
象的特性。但是不要被愚弄:如果不是后期绑定,就不是多态。多态Rules
for
overridingOverloadingpublic
class
PrivateOverride
{private
static
Test
monitor
=
new
Test();private
void
f()
{System.out.println("private
f()");}public
static
void
main(String[]
args)
{PrivateOverride
po
=
new
Derived();po.f();monitor.expect(new
String[]
{"private
f()"});}}•••••class
Derived
extends
PrivateOverride
{public
void
f()
{System.out.println("public
f()");}}
///:~陷阱:“overriding”私有方法class
Base
{public
void
callFoo()
{foo();}private
void
foo()
{}}•••••class
Child
extends
Base
{private
void
foo()
{}}Usage
is
like
the
following:••Child
c
=
new
Child();c.callFoo();这个呢?继承vs组合组合和继承都允许你在新的类中设置子对象(subobject),组合是显式地这样做
的,而继承则是隐式的。继承和组合的选择InheritanceCompositionAdding
a
new
subclassInheritance
helps
make
code
easier
tochangeChanging
the superclass
interfaceone
little change
to a
superclass
canripple
out
and
require
changes
in
manyother places
in
the
application's
code.The
changeCode
reuse
via
inheritance
ICode
reuse
via
inheritance
IICode
reuse
via
composition
ICode
reuse
via
compositioIt
is
easier
to
change
the
interface
of
a
back-end
class
(composition)
than
asuperclass
(inheritance).
As
the
previous
example
illustrated,
a
change
to
theinterface
of
a
back-end
class
necessitates
a
change
to
the
front-end
classimplementation,
but
not
necessarily
the
front-end
interface.
Code
that
dependsonly
on
the
front-end
interface
still
works,
so
long
as
the
front-end
interfaceremains
the
same.
By
contrast,
a
change
to
a
superclass's
interface
can
not
onlyripple
down
the
inheritance
hierarchy
to
subclasses,
but
c so
ripple
out
tocode
that
uses
just
the
subclass's
interface.It
is
easier
to
change
the
interface
of
a
front-end
class
(composition)
than
asubclass
(inheritance).
Just
as
superclasses
can
be
fragile,
subclasses
can
berigid.You
can't
just
change
a
subclass's
interface
without
making
sure
thesubclass's
new
interface
is
compatible
with
that
of
its
supertypes.
For
example,you
can't
add
to
a
subclass
a
method
with
the
same
signature
but
a
differentreturn
type
as
a
method
inherited
from
a
superclass.
Composition,
on
theother
hand,
allows
you
to
change
the
interface
of
a
front-end
class
withoutaffecting
back-end
classes.Comparing
composition
andComposition
allows
you
to delay
the
creation
of
back-end
objectsuntil
(and
unless)
they
are
needed,
as
well
as
changing
the
back-endobjects
dynamically
throughout
the
lifetime
of
the
front-end
object.With
inheritance,
you
get
the
image
of
the
superclass
in
yoursubclass
object
image
as
soon
as
the
subclass
is
created,
and
itremains
part
of
the
subclass
object
throughout
the
lifetime
of
thesubclass.It
is
easier
to add
new
subclasses
(inheritance)
than
it
is
to add
newfront-end classes
(composition),
because
inheritance
comes
withpolymorphism.
If
you
have
a
bit
of
code
that
relies
only
on
asuperclass
interface,
that
code
can
work
with a
new
subclasswithout
change.This
is
not
true
of
composition,
unless
you
usecomposition
with
interfaces.
Used
together,
composition
andinterfaces
make
a
very
powerful
design
tool.The
explicit
method-invocation
forwarding
(ordelegation)
approach
of
composition
will
often
have
aperformance
cost
as
compared
to
inheritance's
singleinvocation
of
an
inherited superclass
methodimplementation.
I
say
"often"
here
because
theperformance
really
depends
on
many
factors,
includinghow
the
JVM
optimizes
the
program
as
it
executes
it.With
both
composition and
inheritance,
changing
theimplementation
(not
the
interface)
of
any
class
is
easy.The
ripple
effect
of
implementation changes
remaininside
the same
class.•Make
sure
inheritance
modelsthe
is-a
relationshipDon't
use
inheritance
just
to
getcode
reuseDon't
use
inheritance
just
to
get
atpolymorphismChoosing
between
inheritance
and
composition•组合技术通常用于你想要在新类中使用现有类的功能而非它的接口的情形。即,你在新类中嵌入某个对象,借其实现你所需要的功能,但新类的用户看到的只是你为新类所定义的接口,而非嵌入对象的接口。为取得此效果,你需要在新类中嵌入一个private
的现有类的对象。有时,允许类的用户直接
新类中的组
份是极具意义的;也就是说,将成员对象 为
public。如果成员对象自身都实现了具体实现的隐藏,那么这种做法就是安全
的。当用户能够了解到你在组装一组部件时,会使得端口更加易于理解。Car对象即为一个好例子:•组合的选择••//:
c06:Car.java//
Composition
with
public
objects.•••••class
Engine
{public
void
start()
{}public
void
rev()
{}public
void
stop()
{}}•••class
Wheel
{public
void
inflate(int
psi)
{}}••••class
Window
{public
void
rollup()
{}public
void
rolldown()
{}}•••••class
Door
{public
Window
window
=
new
Window();public
void
open()
{}public
void
close()
{}}Carpublic
class
Car
{public
Engine
engine
=
new
Engine();public
Wheel[]
wheel
=
new
Wheel[4];public
Doorleft
=
new
Door(),right
=
new
Door();
//
2-doorpublic
Car()
{for(int
i
=
0;
i
<
4;
i++)wheel[i]
=
new
Wheel();}public
static
void
main(String[]
args)
{Car
car
=
new
Car();car.left.window.rollup();car.wheel[0].inflate(72);}}
///:~继承和构造方法Inheritance
and
constructorsHow
to
invoke
a
superclass
constructor?Superclass
constructor
with
argumentsInvoking
one
overloaded
constructor
fromanother
••Access
Main(),
load
base
class,
Load
until
the
rootbase
classStatic
Initialization
in
the
root base
class
then
thenext
derived
class,
and
so
onAll
the
primitives and
the
object
reference
are
setto
nullThe
base-class
constructor
will be
calledThe
instance
variables
are
initialized
in
textualorderThe
rest
of
the
body
of
the
constructor is
executedInitialization
with
inheritance•••••••••••••••••••••class
Characteristic
{private
String
s;Characteristic(String
s)
{this.s
=
s;System.out.println("Creating
Characteristic
"
+
s);}protected
void
dispose()
{System.out.println("finalizing
Characteristic
"
+
s);}}class
Description
{private
String
s;Description(String
s)
{this.s
=
s;System.out.println("Creating
Description
"
+
s);}protected
void
dispose()
{System.out.println("finalizing
Description
"
+
s);}}class
LivingCreature
{private
Characteristic
p
=
new
Characteristic("is
alive");private
Description
t
=new
Description("Basic
Living
Creature");LivingCreature()
{System.out.println("LivingCreature()");}protected
void
dispose()
{System.out.println("LivingCreature
dispose");t.dispose();p.dispose();}}•class
Animal
extends
LivingCreature
{private
Characteristic
p=
new
Characteristic("has
heart");private
Description
t
=new
Description("Animal
not
Vegetable");Animal()
{System.out.println("Animal()");}protected
void
dispose()
{System.out.println("Animal
dispose");t.dispose();p.dispose();super.dispose();}}•••••••••••••••class
Amphibian
extends
Animal
{private
Characteristic
p
=new
Characteristic("can
live
in
water");private
Description
t
=new
Description("Both
water
and
land");Amphibian()
{System.out.println("Amphibian()");}protected
void
dispose()
{System.out.println("Amphibian
dispose");t.dispose();p.dispose();super.dispose();}}public
class
Frog
extends
Amphibian
{private
static
Test
monitor
=
new
Test();private
Characteristic
p
=
new
Characteristic("Croaks");private
Description
t
=
new
Description("Eats
Bugs");public
Frog()
{System.out.println("Frog()");}protected
void
dispose()
{System.out.println("Frog
dispose");t.dispose();p.dispose();super.dispose();}public
static
void
main(String[]
args)
{Frog
frog
=
new
Frog();System.out.println("Bye!");frog.dispose();}•••••••••••••••••••••••••••monitor.expect(new
String[]
{"Creating
Characteristic
is
alive","Creating
Description
Basic
Living
Creature","LivingCreature()","Creating
Characteristic
has
heart","Creating
Description
Animal
not
Vegetable","Animal()","Creating
Characteristic
can
live
in
water","Creating
Description
Both
water
and
land","Amphibian()","Creating
Characteristic
Croaks","Creating
Description
Eats
Bugs","Frog()","Bye!","Frog
dispose","fin
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 五年级数学(小数乘法)计算题专项练习及答案
- 五年级数学(小数四则混合运算)计算题专项练习及答案
- 2025年中国邮政储蓄市场供需格局及未来发展趋报告
- 2025年中国地红霉素行业市场发展监测及投资潜力预测报告
- 2025年活性橙KN-GR项目投资可行性研究分析报告
- 2025年中国防水耐火纸行业市场全景监测及投资前景展望报告
- 房地产教育合作协议书(2篇)
- 2025年便携式电火花取丝锥行业深度研究分析报告
- 2025年中国汽车高压包行业市场深度分析及发展趋势预测报告
- 2024-2030年中国输液泵行业市场深度分析及投资策略研究报告
- 神农架研学课程设计
- 文化资本与民族认同建构-洞察分析
- 2025新译林版英语七年级下单词默写表
- 《锡膏培训教材》课件
- 断绝父子关系协议书
- 福建省公路水运工程试验检测费用参考指标
- 《工程勘察资质分级标准和工程设计资质分级标准》
- 眼内炎患者护理查房课件
- 2021-2022学年四川省成都市武侯区部编版四年级上册期末考试语文试卷(解析版)
- 中国传统文化服饰文化
- 大气污染控制工程 第四版
评论
0/150
提交评论