AP计算机教程9-2:继承
面向对象编程的一个极为有用的特性是继承(inheritance)。在现实生活中你可能有了解继承的概念,即某人获得了逝去亲戚的遗产,或者某人像其父母一样在文体方面展现出才华。Java中的任意class都可以继承另一个class的field和method。被继承的class叫做parent class,获得field和method的class则叫做child class。
当继承关系发生时,我们可以说child class是(is-a)parent class。比如class Car
继承了class Vehicle
,我们就知道汽车是机动车。同理,摩托车也是机动车。所有的机动车都有品牌、型号、出厂年份等信息。机动车也可以前进、后退、左转和右转。
上图这样的统一模型语言(Unified Modeling Language, UML)图示可以表示class之间的关系。空心箭头指向parent class,而Car
和Motorcycle
都继承了Vehicle
。当然反过来这也意味着Vehicle
有两个child class:Car
和Motorcycle
。
指定parent class
我们可以用Java关键字extends
加上class的名字来指定parent class。如下所示。
public class Car extends Vehicle public class Motorcycle extends Vehicle
注意Java在设计上是单继承的,即child class仅可以继承一个parent class,不过parent class可以被多个child class继承。如果在声明class时没有带上extends
关键字,则会隐式继承java.lang.Object
。
为何使用继承?
继承让你方便的重用parent class中的数据和行为。如果你有好几个class提供类似的功能,则可以考虑重构代码,用一个parent class来实现它们所共享的主要功能。比如Customer
和Employee
都是人,则可以用People
来实现它们的交集。如果你将现有的class稍作改动即能满足新的需求,继承也同样会是称手的工具——只要添加额外用到的数据和行为即可。下图体现了重构后Customer
,Employee
和People
的关系。
0:00
If you don’t specify the parent class in a class declaration which of the following is true?
java.lang.Object
。If the class Vehicle
has object fields of make and model and the class Car
inherits from the class vehicle will a car object have a make and model?
If I had a class ParkingGarage
should it inherit from the class Vehicle
?
ParkingGarage
不是Vehicle
。In Java how many parents can a class have?
0 条评论