Polymorphism I CMSC 202

Similar documents
Java CPD (I) Frans Coenen Department of Computer Science

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

Object-Oriented Programming: Polymorphism

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

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

Inheritance, overloading and overriding

Comp 248 Introduction to Programming

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

Fundamentals of Java Programming

CS193j, Stanford Handout #10 OOP 3

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

AP Computer Science Java Subset

CMPT 183 Foundations of Computer Science I

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

Introduction to Object-Oriented Programming

CS170 Lab 11 Abstract Data Types & Objects

Description of Class Mutation Mutation Operators for Java

History OOP languages Year Language 1967 Simula Smalltalk

Java Interview Questions and Answers

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

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

Link-Time Static Analysis for Efficient Separate Compilation of Object-Oriented Languages

Object-Oriented Programming in Java

Java Programming Language

Chapter 13 - Inheritance

Remote Method Invocation

A Comparison of the Object-Oriented Features of Ada 95 and Java

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

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

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Introduction to Object-Oriented Programming

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer

Android Application Development Course Program

Programmation 2. Introduction à la programmation Java

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

CSE 1020 Introduction to Computer Science I A sample nal exam

Chapter 1 Fundamentals of Java Programming

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

LAB4 Making Classes and Objects

Building Java Programs

Inheritance in Programming Languages

Glossary of Object Oriented Terms

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

AP Computer Science Java Mr. Clausen Program 9A, 9B

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

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 Software Design

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Effective unit testing with JUnit

Managing Variability in Software Architectures 1 Felix Bachmann*

Class 16: Function Parameters and Polymorphism

D06 PROGRAMMING with JAVA

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

CSE 452: Programming Languages. Acknowledgements. Contents. Java and its Evolution

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

Building Java Programs

JAVA - OBJECT & CLASSES

1001ICT Introduction To Programming Lecture Notes

Java SE 7 Programming

Java SE 7 Programming

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

Advanced Data Structures

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Introduction to Object-Oriented Programming

Contents. Java - An Introduction. Java Milestones. Java and its Evolution

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

Distributed objects and object-based middleware

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

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

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

Introducing Variance into the Java Programming Language DRAFT

Introduction to Java. CS 3: Computer Programming in Java

Chapter 2: Elements of Java

1. Polymorphism in C++...2

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

CMSC 202H. ArrayList, Multidimensional Arrays

Web-Service Example. Service Oriented Architecture

Division of Informatics, University of Edinburgh

C++ INTERVIEW QUESTIONS

Tutorial on Writing Modular Programs in Scala

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

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

6.1. Example: A Tip Calculator 6-1

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

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

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

ICOM 4015: Advanced Programming

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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Copyright 2008 The Pragmatic Programmers, LLC.

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

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Object Oriented Programming Design Basics CMSC 202

Graduate Assessment Test (Sample)

DIPLOMADO DE JAVA - OCA

Course Title: Software Development

Transcription:

Polymorphism I CMSC 202

Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with methods classes 2

Introduction to Polymorphism Object-oriented programming mechanisms Encapsulation - data and methods together Inheritance - extending a class for specialization Polymorphism Polymorphism The ability to associate many meanings with one method name. Accomplished through a mechanism known as late binding or dynamic binding. Copyright 2008 Pearson Addison-Wesley. All rights reserved 3

Vehicle Hierarchy Vehicle Automobile Aircraft Watercraft 4

Identifying Classes of Vehicles public class Vehicle { public void identify(){ System.out.println("Vehicle"); public class Automobile extends Vehicle { public void identify(){ System.out.println("Automobile"); public class Aircraft extends Vehicle { public void identify(){ System.out.println("Aircraft"); public class Watercraft extends Vehicle { public void identify(){ System.out.println("Watercraft"); We have implemented the identify() method defined in the base class and overidden in the derived classes. Each is a more specific definition of the base class' method. 5

The Vehicle Classes In the VehicleDemo, we ask each Vehicle to identify itself. This is a poor example of OOP as we will see... public class VehicleDemo { public void identifyyourself(automobile a){ a.identify(); public void identifyyourself(aircraft a){ a.identify(); public void identifyyourself(watercraft a){ a.identify(); Output public static void main(string[] args){ Automobile m = new Automobile(); Watercraft w = new Watercraft(); Aircraft a = new Aircraft(); VehicleDemo demo = new VehicleDemo(); demo.identifyyourself(m); demo.identifyyourself(a); demo.identifyyourself(w); Automobile Aircraft Watercraft 6

Problems with VehicleDemo? The VehicleDemo class contains a typespecific version of identifyyourself for each type of Vehicle. What if we add more types of Vehicles? Wouldn t it be nice to write just one identifyyourself method that works for all Vehicles? 7

NewVehicleDemo public class NewVehicleDemo { public void identifyyourself(vehicle v){ v.identify(); public static void main(string[] args){ Automobile m = new Automobile(); Watercraft w = new Watercraft(); Aircraft a = new Aircraft(); Output Automobile Aircraft Watercraft NewVehicleDemo demo = new NewVehicleDemo(); demo.identifyyourself(m); demo.identifyyourself(a); demo.identifyyourself(w); 8

How Does NewVehicleDemo work? Associating the appropriate method definition with the method invocation is known as binding. Early binding occurs when the method definition is associated with its invocation when code is compiled. With early binding, the method invoked is determined by the reference variable type. How can the compiler know which Vehicle's identify method to call in identifyyourself? It can t! 9

Late Binding The solution is to use late (dynamic) binding. Late binding The appropriate method definition is associated with its invocation at run-time. The method invoked is determined by the type of object to which the variable refers, NOT by the type of the reference variable. Java uses late binding for all methods except final, private (which are implicitly final), and static methods. 10

An Object Knows the Definitions of Its Methods The type of a class variable determines which method names can be used with the variable. However, the object named by the variable determines which definition with the same method name is used. Vehicle v = new Automobile(); Vehicle type variable A special case of this rule: v FF08 Object named Automobile The type of a class variable determines which method names and members the compiler recognizes for the parameter. The argument determines which definition of the method name is used. 11

Using Polymorphism How do we take advantage of Polymorphism? Write code to talk to base class objects (e.g. use base class references as method parameters) Late binding will ensure that the appropriate method definition is used, even if a reference to a derived class is passed to the method. 12

More Vehicles Vehicle Automobile Watercraft Aircraft Car Motorcycle Boat Jet Skit Helicopter Jet 13

Extensibility Suppose more Vehicles were added to the hierarchy as shown in the previous diagram. All of these new classes work correctly with the old, unchanged identify() method of the NewVehicleDemo class because identifyyourself() s parameter is a base class reference type(vehicle). In a well designed OOP program, most of your methods will follow the model of identifyyourself() and communicate with a base class reference and let late binding and polymorphism determine which class' identify() method to call. Such a program is called extensible because you can add new functionality by deriving new classes from the base class without changing existing code. 14

The final Modifier A method marked final indicates that it cannot be overridden with a new definition in a derived class. If final, the compiler can use early binding with the method. public final void somemethod() {... A class marked final indicates that it cannot be used as a base class from which to derive any other classes. Copyright 2008 Pearson Addison-Wesley. All rights reserved 15

Late Binding with tostring Because all classes created extend from Object, our classes inherit the tostring method and can be printed using System.out.println( ); as in this code snippet: Vehicle auto = new Automobile( ); System.out.println(auto); This works because of late binding. 16

Late Binding with tostring One definition of the method println takes a single argument of type Object: public void println(object theobject) { System.out.println(theObject.toString()); In turn, It invokes the version of println that takes a String argument. Note that the println method was defined before the Vehicle class existed. Because of late binding, the tostring method from the Vehicle class is used, not the tostring from the Object class. Copyright 2008 Pearson Addison-Wesley. All rights reserved 17

Upcasting and Downcasting Upcasting occurs when an object of a derived class is assigned to a variable of a base class (or any ancestor class). Vehicle v; // base class Automobile auto = new Automobile(); // derived class v = auto; // upcasting v.identify(); // prints automobile Or we could do something equivalent, such as Vehicle v = new Automobile(); Because of late binding, identify() uses the definition of identify() given in the Automobile class. Copyright 2008 Pearson Addison-Wesley. All rights reserved 18

Upcasting and Downcasting Downcasting occurs when a type cast is performed from a base class to a derived class (or from any ancestor class to any descendent class). Downcasting must be done very carefully. In many cases it doesn't make sense, or is illegal: void dosomething(vehicle v1) { Automobile a1 = (Automobile) v1; // could generate an error a1 = v1; // will generate an error There are times when downcasting is necessary; e.g., inside the equals method for a class. How can we make sure a Vehicle is an Automobile? 19