Polymorphi sm. 2 Abstract Classes Java allows abstract classes – use the modifier abstract on a class header to declare an abstract class abstract class.

Slides:



Advertisements
Similar presentations
Interfaces A Java interface is a collection
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
More Inheritance Abstract Classes Interfaces Briana B. Morrison CSE 1302C Spring 2010.
9. Inheritance 9.1 Subclasses 9.2 Polymorphism 9.3 Abstract Classes 9.4 Modifiers and Access 9.6 Object-Oriented Design with Use Cases and Scenarios.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
Abstract Classes b b An abstract class is a placeholder in a class hierarchy that represents a generic concept b b An abstract class cannot be instantiated.
INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.
Polymorphism Pure Object Oriented Programming. Announcements Office Hours next Tuesday, April 4, 2000 will be from 1:00 - 2:00 p.m. instead of 3:00 -
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Abstract Classes and Interfaces Lecture 2 – 9/6/2012.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Coming up: Inheritance
© 2004 Pearson Addison-Wesley. All rights reserved April 14, 2006 Polymorphism ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Side effects A side effect is anything that happens in a method other than computing and/or returning a value. Example: public class hello { public int.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
1 Lecture 8 b Data Structures b Abstraction b The “Structures” package b Preconditions and postconditions b Interfaces b Polymorphism b Vector class b.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
2/23- Interfaces Reference: Java 6.5 and 9.3. PA-4 Review Requirements PA3 – Grading Key PA4 Requirements Doc.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Introduction to Polymorphism. Recall We set out to explore a new language, Java, which uses the Object Oriented Paradigm. We claimed that it would allow.
Chapter 5: Enhancing Classes
Polymorphism.
Inheritance and Polymorphism
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
Designing for Inheritance
Class Inheritance (Cont.)
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Chapter 5: Enhancing Classes
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Chapter 9 Carrano Chapter 10 Small Java
2009 Test Key.
Object-Oriented Design Part 2
Presentation transcript:

Polymorphi sm

2 Abstract Classes Java allows abstract classes – use the modifier abstract on a class header to declare an abstract class abstract class Vehicle { … } An abstract class is a placeholder in a class hierarchy that represents a generic concept Vehicle CarBoatPlane

3 Abstract Class: Example public abstract class Vehicle { String name; public String getName() { return name; } \\ method body abstract public void move(); \\ no body! } r An abstract class often contains abstract methods, though it doesn’t have to m Abstract methods consist of only methods declarations, without any method body

4 Abstract Classes An abstract class often contains abstract methods, though it doesn’t have to – Abstract methods consist of only methods declarations, without any method body The non-abstract child of an abstract class must override the abstract methods of the parent An abstract class cannot be instantiated (why?) The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate

5 Recap: References and Inheritance An object reference variable can refer to any object instantiated from – its own class, or – any class derived from it by inheritance For example, Holiday day; day = new Holiday(); … day = new Christmas(); Holiday Christmas The assignment of an object of a derived class to a reference variable of the base class can be considered as a widening conversion

6 References and Inheritance Through a given type of reference variable, we can invoke only the methods defined in that type Can we do the following statements: day.celebrate(); day.listenToChristmasSongs(); Holiday day; day = new Christmas(); class Holiday { public void celebrate() {…} } class Christmas extends Holiday { public void celebrate() {…} public void listenToChristmasSongs() {…} }

7 References and Inheritance We can “promote” an object back to its original type through an explicit narrowing cast: Holiday day = new Christmas(); day.celebrate(); … Christmas c = (Christmas) day; c.listenToChristmasSongs(); Question: which celebrate() will be invoked by the line: day.celebrate();

8 Java Interface A Java interface is a collection of constants and abstract methods – abstract method: a method header without a method body; we declare an abstract method using the modifier abstract – since all methods in an interface are abstract, the abstract modifier is usually left off Methods in an interface have public visibility by default

9 Interface: Syntax public interface Doable { public static final String NAME; public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } interface is a reserved word No method in an interface has a definition (body) A semicolon immediately follows each method header

10 Implementing an Interface A class formally implements an interface by – stating so in the class header in the implements clause – a class can implement multiple interfaces: the interfaces are listed in the implements clause, separated by commas If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors

11 Implementing Interfaces public class Something implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition public class ManyThings implements Doable, AnotherDoable

12 Interfaces: Examples from Java Standard Class Library The Java Standard Class library defines many interfaces: – the Iterator interface contains methods that allow the user to move through a collection of objects easily hasNext(), next(), remove() – the Comparable interface contains an abstract method called compareTo, which is used to compare two objects if (obj1.compareTo(obj2) < 0) System.out.println(“obj1 is less than obj2”);

13 Polymorphism via Interfaces Define a polymorphism reference through interface – declare a reference variable of an interface type Doable obj; – the obj reference can be used to point to any object of any class that implements the Doable interface – the version of doThis depends on the type of object that obj is referring to: obj.doThis();

14 Interface Hierarchies Inheritance can be applied to interfaces as well as classes One interface can be used as the parent of another The child interface inherits all abstract methods of the parent A class implementing the child interface must define all methods from both the parent and child interfaces Note that class hierarchies and interface hierarchies are distinct (they do not overlap)

Scenarios A veterinarian's algorithm might have a list of animals, but each one needs different food or care… we want ONE information system to track all of this without complex logic for each individual kind of animal. A car dealership sells many different types of cars with different features, but each has a price and quantity in stock. A registration system might treat in-state students differently from out-of-state students, graduate students differently from undergraduates, etc. A graphical user interface (GUI) e.g. Windows needs to puts lots of simlar widgets on screen... LB

Motivation We’d like to be able to manage objects of different kinds of classes. Since classes within a class hierarchy often share common methods and attributes, we’d like to make use of this fact to make our algorithms simpler.

Polymorphism Defined The ability to take on different forms. Manipulate objects of various classes, and invoke methods on an object without knowing that object’s type.

A Class Hierarchy Animal DogCatFish MuttPoodleGoldBeta

A Polymorphic Example Animal Dog Mutt MyMutt isoftype Mutt MyAnimal isoftype Animal MyDog isoftype Dog... MyDog <- MyMutt MyAnimal <- MyMutt

Polymorphism Explained MyAnimal <- MyMutt seems incorrect. The left and right hand side of the assignment seem to not match; or do they? Since Mutt inherits from Dog, and Dog inherits from Animal, then MyMutt is at all times a Mutt, a Dog, and an Animal. Thus the assignment statement is perfectly valid. This makes logical (“real world”) sense.

An Illegal Example We are able to assign an object of a sub-class into an object of a super-class as in: MyAnimal <- MyMutt But the reverse is not true. We can’t assign a superclass object into a sub-class object. MyMutt <- MyAnimal // illegal

Method Calls and Polymorphism Assume the Dog class inherits the Animal class, redefining the “MakeNoise” method. Consider the following: MyAnimal <- MyDog MyAnimal.MakeNoise

Method Calls and Polymorphism MyAnimal <- MyDog MyAnimal.MakeNoise Different languages handle this differently. For simplicity, we’ll assume that MyAnimal “remembers” it is actually an object of the Dog class, so we’ll execute the MakeNoise method in the Dog class.

Polymorphism vs. Inheritance Inheritance is required in order to achieve polymorphism (we must have class hierarchies). – Re-using class definitions via extension and redefinition Polymorphism is not required in order to achieve inheritance. – An object of class A acts as an object of class B (an ancestor to A).

Processing Collections One of the main benefits of polymorphism is the ability to easily process collections. We will consider a collection (queue) of bank accounts in the next example...

The Banking Class Hierarchy Cool Savings Bank Account Savings Account Checking Account NOW Account Money Market Account CD Account

A Collection of Bank Accounts Imagine a bank needs to manage all of the accounts. Rather than maintain seven separate queues, one each for: Bank_Accounts, Savings_Accounts, Cool_Savings, CD_Accounts, Checking_Accounts, NOW_accounts, and Money_Market_Accounts We can maintain only one queue of Bank Accounts.

Polymorphic Banking Assume accounts of various kinds: john_account isoftype Checking_Account paul_account isoftype Cool_Savings paul_other_account isoftype CD_Account george_account isoftype NOW_Account ringo_account isoftype Money_Market Then put them all in a single structure: account_queue isoftype Queue(Bank_Account) account_queue.Enqueue(john_account) account_queue.Enqueue(paul_account) account_queue.Enqueue(paul_other_account) account_queue.Enqueue(george_account) account_queue.Enqueue(ringo_account)

Polymorphic Banking account_queue is polymorphic: It is holding accounts of “many forms.” Each of the accounts is “within the family” of the class hierarchy of bank accounts. Each one will have it’s own set of capabilities via inheritance (extension, and/or redefinition).

Resolving Polymorphic Method Calls Different languages do this differently. The various kinds of Accounts, though all stored as a Bank_Account, remember the class (subclass) of which they are an instance. So, calls to Get_Balance() will: – use the method from class NOW_Account if the object is an instance of NOW_Account – use the method from class Money_Market if the object is an instance of Money_Market – and so on...

Polymorphism This is the “magic” of polymorphism…it keeps track of family members within the inheritance hierarchy for you. Without it, we’d have lots of code sprinkled through out our algorithm choosing among many options: if( it’s Checking_Account ) then call Checking_Account Calc_Interest elseif( it’s Super_Savings) then call Super_Savings Calc_Interest elseif( it’s CD_Account then call CD_Account Calc_Interest elseif( it’s NOW_Account ) then call NOW_Account Calc_Interest...

Summary Polymorphism allows objects to represent instances of its own class and any of its sublcasses. Polymorphic collections are useful for managing objects with common (ancestor) interfaces. For our purposes, we’ll assume objects “remember” what kind of class they really contain, so method calls are resolved to the original class.

Explain how you would program this