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的位置,看能否能说得通。比如对于BookComicBook,漫画书是书么?因此这个的确可以适用继承关系。如若不然,包含关系可能是更好的选择。



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,BooksMovies作为child class,TitlePriceIDAuthorsDatePublished等作为field是最好的设计。
3

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
3

What Java keyword is used to specify the parent class?

前面两个选项根本不是Java关键字。
3

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

三个说法都对,Java基于继承的多态意味着child class可以随时被作为parent class的类型来使用,但保留对parent class行为的改动。
2


陈 欣

AADPS创始人

发表评论