Inheritance and Polymorphism


The class SummerCourseSession inherits from CourseSession. Just as a class that implements an interface is of that interface type, a class that inherits from another is of that superclass type. Therefore, SummerCourseSession is a CourseSession.

Just as you were taught to prefer interface reference types, you should also prefer base class for the reference type. Assign a new SummerCourseSession to a CourseSession reference:

 CourseSession session = new SummerCourseSession(); 

Even though the session variable is of the type CourseSession, it still refers to a SummerCourseSession in memory.

You defined the method getEndDate in both CourseSession and SummerCourseSession. When you send the getEndDate message using the session variable, the message is received by a SummerCourseSession object. Java executes the version of getEndDate defined in SummerCourseSession.

The client thinks it is sending a message to a CourseSession, but an object of a class derived from CourseSession receives and interprets the message. This is another example of polymorphism.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net