Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.



Similar documents
SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

The Interface Concept

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

History OOP languages Year Language 1967 Simula Smalltalk

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Contents. 9-1 Copyright (c) N. Afshartous

AP Computer Science Java Subset

Inheritance, overloading and overriding

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java Interview Questions and Answers

Part I. Multiple Choice Questions (2 points each):

Introduction to Object-Oriented Programming

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Java CPD (I) Frans Coenen Department of Computer Science

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

Java Programming Language

CMSC 202H. ArrayList, Multidimensional Arrays

Java (12 Weeks) Introduction to Java Programming Language

CS-XXX: Graduate Programming Languages. Lecture 25 Multiple Inheritance and Interfaces. Dan Grossman 2012

Basic Object-Oriented Programming in Java

Software Engineering Techniques

Introducing Variance into the Java Programming Language DRAFT

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Chapter 1 Fundamentals of Java Programming

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Lecture J - Exceptions

C++ INTERVIEW QUESTIONS

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CS 111 Classes I 1. Software Organization View to this point:

J a v a Quiz (Unit 3, Test 0 Practice)

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Class 16: Function Parameters and Polymorphism

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Object-Oriented Programming

Introduction: Abstract Data Types and Java Review

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

Introduction to Object-Oriented Programming

Habanero Extreme Scale Software Research Project

Using Inheritance and Polymorphism

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Compile-time type versus run-time type. Consider the parameter to this function:

Object-Oriented Programming

Programmation 2. Introduction à la programmation Java

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

CS193j, Stanford Handout #10 OOP 3

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

Java Application Developer Certificate Program Competencies

Fundamentals of Java Programming

The C Programming Language course syllabus associate level

Advanced Data Structures

Chapter 13 - Inheritance

Abstract Class & Java Interface

CSE 1020 Introduction to Computer Science I A sample nal exam

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Stack Allocation. Run-Time Data Structures. Static Structures

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

Object-Oriented Programming: Polymorphism

public static void main(string[] args) { System.out.println("hello, world"); } }

Object Oriented Design

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Johannes Sametinger. C. Doppler Laboratory for Software Engineering Johannes Kepler University of Linz A-4040 Linz, Austria

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

El Dorado Union High School District Educational Services

Description of Class Mutation Mutation Operators for Java

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Design Patterns. Advanced Software Paradigms (A. Bellaachia) 1

Object-Oriented Programming Lecture 2: Classes and Objects

Introduction to Java

Programming Language Concepts: Lecture Notes

Programming Languages Featherweight Java David Walker

1. Polymorphism in C++...2

Chapter 1 Java Program Design and Development

Computing Concepts with Java Essentials

Teach Yourself Java in 21 Minutes

CS170 Lab 11 Abstract Data Types & Objects

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Crash Course in Java

Object Oriented Software Design

java Features Version April 19, 2013 by Thorsten Kracht

Transcription:

Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding Polymorphism Polymorphism A polymorphic field (the state design pattern) Abstract classes The composite design pattern revisited OOP: Polymorphism 1

Class Hierarchies in Java, Revisited Class Object is the root of the inheritance hierarchy in Java. If no superclass is specified a class inherits implicitly from Object. If a superclass is specified explicitly the subclass will inherit indirectly from Object. Object Shape Circle Line Rectangle Square OOP: Polymorphism 2

Why Polymorphism? // substitutability Shape s; s. s. Shape Circle Line Rectangle // extensibility Shape s; s. s. Shape Circle Line Rectangle Square OOP: Polymorphism 3

Why Polymorphism?, cont. // common interface Shape s; s. s. Circle Shape Line Rectangle Upcast Downcast // upcasting Shape s = new Line(); s. s. OOP: Polymorphism 4

Advantages Advantages/Disadvantages of Upcast Code is simpler to write (and read) Uniform interface for clients, i.e., type specific details only in class code, not in the client code Change in types in the class does not effect the clients If type change within the inheritance hierarchy Used extensively in object-oriented programs Many upcast to Object in the standard library Disadvantages Must explictely downcast if type details needed in client after object has been handled by the standard library (very annoing sometimes). Shape s = new Line(); Line l = (Line) s; // downcast OOP: Polymorphism 5

Static and Dynamic Type The static type of a variable/argument is the declaration type. The dynamic type of a variable/argument is the type of the object the variable/argument refers to. class A{ // body class B extends A{ // body public static void main(string args[]){ A x; // static type A B y; // static type B x = new A(); y = new B(); x = y; // dynamic type A // dynamic type B // dynamic type B OOP: Polymorphism 6

In a bar you say I want a beer! What ever beer you get is okay because your request was very generic In a bar you say I want a Samuel Adams Cherry Flavored beer! Polymorphism, informal If you do not exactly get this type of beer you are allowed to complain In chemistry they talk about polymorph materials as an example H 2 0 is polymorph (ice, water, and steam). OOP: Polymorphism 7

Polymorphism Polymorphism: The ability of a variable or argument to refer at run-time to instances of various classes [Meyer pp. 224]. Shape s = new Shape(); Circle c = new Circle(); Line l = new Line(); Rectangle r = new Rectangle(); s = l; l = s; l = (Line)s // is this legal? // is this legal? // is this legal? The assignment s = l is legal if the static type of l is Shape or a subclass of Shape. This is static type checking where the type comparison rules can be done at compile-time. Polymorphism is constrained by the inheritance hierarchy. OOP: Polymorphism 8

Dynamic Binding class A { void dosomething(){... class B extends A { void dosomething (){... A x = new A(); B y = new B(); x = y; x.dosomething(); // on class A or class B? Binding: Connecting a method call to a method body. Dynamic binding: The dynamic type of x determines which method is called (also called late binding). Dynamic binding is not possible without polymorphism. Static binding: The static type of x determines which method is called (also called early binding). OOP: Polymorphism 9

Dynamic Binding, Example class Shape { void { System.out.println ("Shape"); class Circle extends Shape { void { System.out.println ("Circle"); class Line extends Shape { void { System.out.println ("Line"); class Rectangle extends Shape { void {System.out.println ("Rectangle"); public static void main(string args[]){ Shape[] s = new Shape[3]; s[0] = new Circle(); s[1] = new Line(); s[2] = new Rectangle(); for (int i = 0; i < s.length; i++){ s[i].; // prints Circle, Line, Rectangle OOP: Polymorphism 10

Polymorphish and Constructors class A { // example from inheritance lecture public A(){ System.out.println("A()"); // when called from B the B.doStuff() is called dostuff(); public void dostuff(){system.out.println("a.dostuff()"); class B extends A{ int i = 7; public B(){System.out.println("B()"); public void dostuff(){system.out.println("b.dostuff() " + i); public class Base{ public static void main(string[] args){ B b = new B(); b.dostuff(); //prints A() B.doStuff() 0 B() B.doStuff() 7 OOP: Polymorphism 11

Polymorphish and private Methods class Shape { void { System.out.println ("Shape"); private void dostuff() { System.out.println("Shape.doStuff()"); class Rectangle extends Shape { void {System.out.println ("Rectangle"); public void dostuff() { System.out.println("Rectangle.doStuff()"); public class PolymorphShape { public static void polymorphismprivate(){ Rectangle r = new Rectangle(); r.dostuff(); // okay part of Rectangle interface Shape s = r; // up cast s.dostuff(); // not allowed, compiler error OOP: Polymorphism 12

Why Polymorphism and Dynamic Binding? Separate interface from implementation. What we are trying to achieve in object-oriented programming! Allows programmers to isolate type specific details from the main part of the code. Client programs only use the method provided by the Shape class in the shape hierarchy example. Code is simpler to write and to read. Can change types (and add new types) with this propagates to existing code. OOP: Polymorphism 13

Overloading vs. Polymorphism (1) Has not yet discovered that the Circle, Line and Rectangle classes are related. (not very realisitic but just to show the idea). Circle OverloadClient Line Rectangle Usage not inheritence OOP: Polymorphism 14

Overloading vs. Polymorphism (2) class Circle { void { System.out.println("Circle"); class Line { void { System.out.println("Line"); class Rectangle { void { System.out.println("Rectangle"); public class OverloadClient{ // make a flexible interface by overload and hard work public void dostuff(circle c){ c.; public void dostuff(line l){ l.; public void dostuff(rectangle r){ r.; public static void main(string[] args){ OverloadClient oc = new OverloadClient(); Circle ci = new Circle(); Line li = new Line(); Rectangle re = new Rectangle(); // nice encapsulation from client oc.dostuff(ci); oc.dostuff(li); oc.dostuff(re); OOP: Polymorphism 15

Overloading vs. Polymorphism (3) Discovered that the Circle, Line and Rectangle class are related are related via the general concept Shape Client only needs access to base class methods. PolymorphClient Shape Circle Line Rectangle OOP: Polymorphism 16

Overloading vs. Polymorphism (4) class Shape { void { System.out.println("Shape"); class Circle extends Shape { void { System.out.println("Circle"); class Line extends Shape { void { System.out.println("Line"); class Rectangle extends Shape { void { System.out.println("Rectangle"); public class PolymorphClient{ // make a really flexible interface by using polymorphism public void dostuff(shape s){ s.; public static void main(string[] args){ PolymorphClient pc = new PolymorphClient(); Circle ci = new Circle(); Line li = new Line(); Rectangle re = new Rectangle(); // still nice encapsulation from client pc.dostuff(ci); pc.dostuff(li); pc.dostuff(re); OOP: Polymorphism 17

Overloading vs. Polymorphism (5) Must extend with a new class Square and the client has still not discovered that the Circle, Line, Rectangle, and Square classes are related. Circle OverloadClient Line Rectangle Square OOP: Polymorphism 18

Overloading vs. Polymorphism (6) class Circle { void { System.out.println("Circle"); class Line { void { System.out.println("Line"); class Rectangle { void { System.out.println("Rectangle"); class Square { void { System.out.println("Square"); public class OverloadClient{ // make a flexible interface by overload and hard work public void dostuff(circle c){ c.; public void dostuff(line l){ l.; public void dostuff(rectangle r){ r.; public void dostuff(square s){ s.; public static void main(string[] args){ <snip> // nice encapsulation from client oc.dostuff(ci); oc.dostuff(li); oc.dostuff(re); OOP: Polymorphism 19

Overloading vs. Polymorphism (7) Must extend with a new class Square that is a subclass to Rectangle. PolymorphClient Shape Circle Line Rectangle Square OOP: Polymorphism 20

Overloading vs. Polymorphism (8) class Shape { void { System.out.println("Shape"); class Circle extends Shape { void { System.out.println("Circle"); class Line extends Shape { void { System.out.println("Line"); class Rectangle extends Shape { void { System.out.println("Rectangle"); class Square extends Rectangle { void { System.out.println("Square"); public class PolymorphClient{ // make a really flexible interface by using polymorphism public void dostuff(shape s){ s.; public static void main (String[] args){ <snip> // still nice encapsulation from client pc.dostuff(ci); pc.dostuff(li); pc.dostuff(re); OOP: Polymorphism 21

Open Closed The Opened/Closed Principle The class hierarchy can be extended with new specialized classes. The new classes added do not affect old clients. The superclass interface of the new classes can be used by old clients. This is made possible via Polymorphism Dynamic binding Try to do this in C or Pascals! OOP: Polymorphism 22

A Polymorph Field A scientist does three very different things Writes paper (and drinking coffee) Teaches classes (and drinking water) Administration (and drinking tea) The implementation of each is assumed very complex Must be able to change dynamically between these modes Scientist mode Mode work() drink() WriteMode work() drink() TeachMode work() drink() AdmMode work() drink() OOP: Polymorphism 23

Implementing a Polymorph Field public class Mode{ public void work(){ System.out.println(""); public void drink(){ System.out.println(""); public class WriteMode extends Mode{ public void work(){ System.out.println("write"); public void drink(){ System.out.println("coffee"); public class TeachMode extends Mode{ public void work(){ System.out.println("teach"); public void drink(){ System.out.println("water"); public class AdmMode extends Mode{ public void work(){ System.out.println("administrate"); public void drink(){ System.out.println("tea"); OOP: Polymorphism 24

Implementing a Polymorph Field, cont. public class Scientist{ private Mode mode; public Scientist(){ mode = new WriteMode(); /* default mode */ // what scientist does public void doing() { mode.work(); public void drink() { mode.drink(); // change modes methods public void setwrite() { mode = new WriteMode(); public void setteach() { mode = new TeachMode(); public void setadministrate() { mode = new AdmMode(); public static void main(string[] args){ Scientist einstein = new Scientist(); einstein.doing(); einstein.setteach(); einstein.doing(); OOP: Polymorphism 25

Evaluation of the Polymorph Field Can change modes dynamically Main purpose! Different modes are isolated in separate classes Complexity is reduced (nice side-effect) Client of the Scientist class can see the Mode class (and its supclasses). This may unecessarily confuse these clients. Scientist class cannot change mode added after it has been compiled, e.g., SleepMode. Can make instances of Mode class. This should be prevented. The state design pattern Nice design! OOP: Polymorphism 26

Abstract Class and Method An abstract class is a class with an abstract method. An abstract method is method with out a body, i.e., only declared but not defined. It is not possible to make instances of abstract classes. Abstract method are defined in subclasses of the abstract class. OOP: Polymorphism 27

Abstract Class and Method, Example C1 d2 d1 A B C Abstract Concrete Abstract class C1 with abstract methods A and B C2 d4 d3 A Abstract class C2. Defines method A but not method B. Adds data elements d3 and d4 C3 d5 B D E Concrete class C3. Defines method B. Adds the methods D and E and the data element d5. OOP: Polymorphism 28

Abstract Classes in Java abstract class ClassName { // <class body> Classes with abstract methods must declared abstract. Classes without abstract methods can be declared abstract. A subclass to a concrete superclass can be abstract. Constructors can be defined on abstract classes. Instances of abstract classes cannot be made. Abstract fields not possible. OOP: Polymorphism 29

Abstract Class in Java, Example // [Source: Kurt Nørmark] public abstract class Stack{ abstract public void push(object el); abstract public void pop(); // note no return value abstract public Object top(); abstract public boolean full(); abstract public boolean empty(); abstract public int size(); public void toggletop(){ if (size() >= 2){ Object topel1 = top(); pop(); Object topel2 = top(); pop(); push(topel1); push(topel2); public String tostring(){ return "Stack"; OOP: Polymorphism 30

Abstract Methods in Java abstract [access modifier] return type methodname([parameters]); A method body does not have be defined. Abstract method are overwritten in subclasses. Idea taken directly from C++ pure virtual function You are saying: The object should have this properties I just do not know how to implement the property at this level of abstraction. OOP: Polymorphism 31

The Composite Design Pattern Client use Single print() Component print() add() remove() List print() add() remove() components for all components c c.print() Component class in italic means abstract class Single typically called leaf List typically called composite OOP: Polymorphism 32

Implementation of The Compsite Pattern public abstract class Component{ public abstract void print(); // no body public void add(component c){ // still concrete! System.out.println("Do not call add on me!"); public void remove(component c){ // still concrete! System.out.println("Do not call add on me!"); public class Single extends Component{ private String name; public Single(String n){ name = n; public void print(){ System.out.println(name); public class List extends Component{ private Component[] comp; private int count; public List(){ comp = new Component[100]; count = 0; public void print(){ for(int i = 0; i <= count - 1; i++){ comp[i].print(); // polymorphism public void add(component c){ comp[count++] = c; OOP: Polymorphism 33

Evaluation of the Composite Design Pattern Made List and Single classes look alike when printing from the client's point of view. The main objective! Can make instances of Component class, not the intension Can call dummy add/remove methods on these instances (FIXED) Can call add/remove method of Single objects, not the intension. (CANNOT BE FIXED). Fixed length, not the intension. Nice design! The Mode class from the Science example should also be an abstract class. OOP: Polymorphism 34

Summary Polymorphism an object-oriented switch statement. Polymorphism should strongly be prefered over overloading Must simpler for the class programmer Identical (almost) to the client programmer Polymorphism is a prerequest for dynamic binding and central to the object-oriented programming paradigm. Sometimes polymorphism and dynamic binding are described as the same concept (this is inaccurate). Abstract classes Complete abstract class no methods are abstract but instatiation does not make sense. Incomplete abstract class, some method are abstract. OOP: Polymorphism 35

Abstract Methods in Java, Example public abstract class Number { public abstract int intvalue(); public abstract long longvalue(); public abstract double doublevalue(); public abstract float floatvalue(); public byte bytevalue(){ // method body public short shortvalue(){ // method body OOP: Polymorphism 36