Download presentation
Presentation is loading. Please wait.
1
Some more concepts
2
Objectives How a single line of code, representing a message—for example, x.foo();—can exhibit a variety of different behaviors at run time How we can specify what an object’s mission should be without going to the trouble of specifying the details of how the object is to carry out that mission, and also under what circumstances we’d want to be able to do so How an object can have a “split personality” by exhibiting the behaviors of two or more different types of object Creative ways for an entire class of objects to easily and efficiently share data without breaking the spirit of encapsulation How features can be defined that are associated with a class as a whole rather than with an instance of a class, and how we can take advantage of this capability to design utility classes How we may declare variables whose values, once assigned, remain constant while an application is executing
3
Polymorphism The term polymorphism refers to the ability of two or more objects belonging to different classes to respond to exactly the same message (method call) in different class-specific ways. As an example, if we were to instruct three different people—a surgeon, a hair stylist, and an actor—to “Cut!”, then The surgeon would begin to make an incision. The hair stylist would begin to cut someone’s hair. The actor would abruptly stop acting out the current scene, awaiting directorial guidance.
4
Polymorphism Simplifies Code Maintenance
If we hadn’t had polymorphism It is robust to change for (Student s : studentBody) { // Process the next student. // Pseudocode. if (s is an undergraduate student) s.printAsUndergraduateStudent(); else if (s is a graduate student) s.printAsGraduateStudent(); else if ... }
5
Three Distinguishing Features of an Object-Oriented Programming Language
(Programmer creation of) user-defined types Inheritance Polymorphism
6
The Benefits of User-Defined Types
easier-to-verify requirements less code to write from scratch when building an application minimize data redundancy—each item of data is stored once, in the object to which it belongs—thereby lessening the likelihood of data integrity errors across an application. insulate our application against ripple effects if private details of a class must change after deployment, thereby dramatically reducing maintenance costs. easier to isolate errors in an application’s (business) logic
7
The Benefits of Inheritance and Polymorphism
The following are among the benefits of inheritance: We can extend already deployed code without having to change and then retest it, resulting in dramatically reduced maintenance costs. Subclasses are much more succinct, which means less code overall to write/maintain. The following is one of the benefits of polymorphism: It minimizes “ripple effects” on client code when new subclasses are added to the class hierarchy of an existing application, resulting in dramatically reduced maintenance costs.
8
Abstract Classes Suppose we define three types of courses
Lab course, Instruction course, and Personal course All the three classes differ in the way they schedule their timings That means we need to have a establishCourseSchedule method for all of them We also want to take advantage of polymorphism What to do?
9
Abstract classes An abstract class is used to define what behaviors a class is required to perform without having to provide an explicit implementation of how each and every such behavior will be carried out. We program an abstract class in much the same way that we program a non-abstract class (aka a concrete class), with one exception: for those behaviors for which we can’t (or care not to) program a generic implementation, we’re permitted to specify method headers without having to program the corresponding method bodies. We refer to a “bodiless,” or header-only, method declaration as an abstract method. And, to differentiate such methods from methods with bodies, we’ll refer to the latter as implemented methods.
10
Abstract Classes Whenever a class contains one or more abstract methods, then we must declare the class abstract as a whole by inserting the abstract keyword ahead of the class keyword in the class declaration: public abstract class Course { ... } By declaring a class abstract, we are telling all of its sub-class what to do but not how to do it. This is accomplished by requiring each of the subclasses to override the abstract method with an implemented version; stated simply, it is accomplished by having each subclass implement the abstract method.
11
Implementing Abstract Methods
There are two options: Either the sub-classes override all the abstract methods of the abstract class Or the sub-class should declare itself abstract
12
Abstract Classes and Instantiation
Abstract classes cannot be instantiated.
13
Declaring Reference Variables of Abstract Types
Despite the fact that we’re prevented from instantiating an abstract class, we’re nonetheless permitted to declare reference variables to be of an abstract type; this is necessary to facilitate polymorphism, as in the following code: for (Course c : courses) { c.establishCourseSchedule(...); } Here, we’re declaring c to be of type Course at compile time, knowing that, at run time, c will actually be referring to an object belonging to a specific concrete subclass of Course, for reasons that we discussed earlier.
14
An Interesting Twist on Polymorphism
it’s possible for a concrete method in an abstract class to invoke an abstract method in the same class. public abstract class Course { // Details omitted. // An abstract method ... public abstract void establishCourseSchedule(String startDate, String endDate); // ... and a concretely implemented method that INVOKES the // abstract method. public void initializeCourse(Professor p, String s, String e) { this.assignInstructor(p); this.reserveClassroom(); // Here, we're invoking an abstract method -- HOW IS THIS POSSIBLE??? establishCourseSchedule(s, e); }
15
Interfaces Suppose we only wanted to specify common behaviors of Courses, and not even bother with declaring attributes? As an example, say that we wanted to define what it means to teach at a university. Perhaps, in order to teach, an object would need to be able to perform the following services: Agree to teach a particular course. Designate a textbook to be used for the course. Define a syllabus for the course. Approve the enrollment of a particular student in the course. our intention is to declare a set of abstract method headers to define what it means to assume a certain role within an application (such as teaching) without imposing either data structure or concrete behavior on the subclasses, then the preferred way to do so in Java is with an interface.
16
Intefaces // Note use of "interface" vs. "class" keyword.
public interface Teacher { boolean agreeToTeach(Course c); void designateTextbook(TextBook b, Course c); Syllabus defineSyllabus(Course c); boolean approveEnrollment(Student s, Course c); } Inteface methods cannot be private Because all of the methods prescribed by an interface are abstract, none of them have bodies.
17
Implementing Interfaces
We do not extend an interface, we implement it Once a class declares that it’s implementing an interface, the implementing class must implement all of the (implicitly abstract) methods declared by the interface in question in order to satisfy the compiler. // Implementing an interface ... public class Professor implements Teacher { ... }
18
Interface or Abstract Class?
When should we use one versus the other? If we wish to impart a particular data structure to go along with these prescribed behaviors, or if we need to provide some concrete behaviors along with abstract behaviors, we’ll create an abstract class. Otherwise, we’ll create an interface.
19
Interface or Abstract Class? Syntactical Differences
20
Interface or Abstract Class? Syntactical Differences
21
Another Form of the “Is A” Relationship
Implementing an interface is another form of “is a” relationship; that is, If the Professor class extends the Person class, then a Professor is a Person. If the Professor class implements the Teacher interface, then a Professor is a Teacher When a class A implements an interface X, all of the classes that are subsequently derived from A may also be said to implement that same interface X. For example, if we derive a class called AdjunctProfessor from Professor, then since Professor implements the Teacher interface, an AdjunctProfessor is a Teacher, as well:
22
Interfaces and Casting
Note that the compiler is perfectly happy for us to assign a Professor object to a Teacher reference variable: Teacher t = new Professor(); The opposite is not permitted, however: we cannot directly assign a Teacher reference to a Professor reference variable, because not all Teachers are necessarily Professors—many different classes can implement the same interface.
23
Interfaces and Casting
if we know that, based on the way we’ve written our code, t will be referring to a Professor object at run time, we may force the assignment through the use of a cast as follows: Professor p1 = new Professor(); Teacher t; t = p1; // We assign a Professor reference to t. Professor p2 = (Professor) t;
24
Implementing Multiple Interfaces
Only one abstract class can be extended However, more than one interfaces can be implemented When a class implements more than one interface, its objects are capable of assuming multiple identities or roles in an application; such objects can therefore be “handled” by various types of reference variables
25
Interfaces and Instantiation
As with abstract classes, interfaces cannot be instantiated. That is, if we define Teacher to be an interface, we may not instantiate it directly: Teacher t = new Teacher(); // Impossible! because interfaces don’t have constructors—only classes do, as templates for instantiating objects—and so we’d encounter the following compilation error: Teacher is abstract; cannot be instantiated We can declare variable Teacher t; // This is OK.
26
Interfaces and Polymorphism
Let’s look at an example of polymorphism as it applies to interfaces. We’ll assume that The Professor and Student classes are both derived from the Person class. Professor and Student are sibling classes—neither derives from the other. Person implements the Teacher interface, and thus by virtue of inheritance, both Professor and Student implicitly implement the Teacher interface We may declare a collection to hold Teacher references, and then populate it with a mixtureof Student and Professor object references as follows: ArrayList<Teacher> teachers = new ArrayList<Teacher>(); teachers.add(new Student("Becky Elkins")); teachers.add(new Professor("Bobby Cranston")); We may then iterate through the teachers collection in polymorphic fashion, referring to all of its elements as Teachers: for (Teacher t : teachers) { t.agreeToTeach(c); // This line of code is polymorphic. }
27
The Importance of Interfaces
Interfaces are one of the most poorly understood, and hence underused, features of the OO programming languages that support them. This is quite unfortunate, as interfaces are extremely powerful if used properly. Whenever possible/feasible when designing classes, if we use interface types rather than specific class types in declaring • (Private) attributes • Formal parameters to methods • Method return types our classes will be more flexible in terms of how client code can use them.
28
The final Keyword A final variable is a variable that can be assigned a value only once in a program; after that first assignment, the variable’s value cannot be changed. We declare such a variable by placing the final keyword just before the type of the variable, as follows: public class Example { // A static variable can be declared to be final ... public static final int x; // ... as can a (nonstatic) attribute. private final int y; public void someMethod() { // Even a local variable may be declared to be final. final int z; // etc.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.