AP计算机教程9-3:包含与继承
class间的另一种常见关系是包含(association)或“有(has-a)”。这种关系意味着class的object中含有另一个class的object的引用。例如,一门课程可能分配到好几个时间段。Course
旁的1
表示单个CoursePeriod
仅与一门Course
关联。CoursePeriod
旁的*
则表示一门Course
可以有任意个CoursePeriod
。
这在Java中往往意味着Course
中可以有一个CoursePeriod
的数组或列表作为field。同时,Course
也作为CoursePeriod
的一个field。
public class Course { private List<CoursePeriod> periodList; } public class CoursePeriod { private Course myCourse; }
替换测试
如果你不确定某个class是否应当继承其他class,你可以试着把child class替换到parent class的位置,看能否能说得通。比如对于Book
和ComicBook
,漫画书是书么?因此这个的确可以适用继承关系。如若不然,包含关系可能是更好的选择。
0:00
A bookstore is working on an on-line ordering system. For each type of published material (books and movies) they need to track the id, title, author(s), date published, and price. Which of the following would be the best design?
PublishedMaterial
作为parent class,Books
和Movies
作为child class,Title
、Price
、ID
、Authors
、DatePublished
等作为field是最好的设计。A movie theater has multiple showings of a movie each day. Each movie showing has a start time and location (theater number). What should the relationship be between class Movie
and class MovieShowing
?
MovieShowing
不是Movie
。What Java keyword is used to specify the parent class?
Which of the following reasons for using an inheritance heirarchy are valid?
I. Object methods from a superclass can be used in a subclass without rewriting or copying code.
II. Objects from subclasses can be passed as arguments to a method that takes an argument of the parent type.
III. Objects from subclasses can be stored in the same array of the parent type.
IV. All of the above
V. None of the above
0 条评论