CHAPTER 9 INTERFACES AND POLYMORPHISM

Similar documents
Chapter 9. Interfaces and Polymorphism. Chapter Goals. Chapter Goals. Using Interfaces for Code Reuse. Using Interfaces for Code Reuse

Interfaces and Polymorphism Advanced Programming

3/7/2012. Chapter Nine: Interfaces and Polymorphism. Chapter Goals

10/27/2011. Chapter Goals

Chapter Nine: Interfaces and Polymorphism. Big Java by Cay Horstmann Copyright 2008 by John Wiley & Sons. All rights reserved.

Chapter 9 Interfaces and Polymorphism. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

COSC This week. Will Learn

Iteration Advanced Programming

public DataSet(Measurer ameasurer) { sum = 0; count = 0; minimum = null; maximum = null; measurer = ameasurer; }

Chapter Goals. Chapter 5 - Iteration. Calculating the Growth of an Investment

Use the scantron sheet to enter the answer to questions (pages 1-6)

Classes, subclasses, subtyping

CSSE 220. Interfaces and Polymorphism. Check out Interfaces from SVN

Introduction to Inheritance

Chapter 5 Object-Oriented Programming

class BankFilter implements Filter { public boolean accept(object x) { BankAccount ba = (BankAccount) x; return ba.getbalance() > 1000; } }

Chapter 9 Inheritance

Intro to Computer Science 2. Inheritance

Chapter Goals. Chapter 7 Designing Classes. Discovering Classes Actors (end in -er, -or) objects do some kinds of work for you: Discovering Classes

ITI Introduction to Computing II

ITI Introduction to Computing II

CH. 2 OBJECT-ORIENTED PROGRAMMING

CS-202 Introduction to Object Oriented Programming

index.pdf January 21,

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

CSCE145 Test 2-Review 03/29/2015 Hongkai Yu

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

Inheritance and Polymorphism

Polymorphism Part 1 1

Introduction to Programming Using Java (98-388)

Container Vs. Definition Classes. Container Class

VIRTUAL FUNCTIONS Chapter 10

CST242 Object-Oriented Programming Page 1

COP 3330 Final Exam Review

Chapter 2. Elementary Programming

Java interface Lecture 15

An introduction to Java II

Object Oriented Programming Exception Handling

Inheritance and Interfaces

COE318 Lecture Notes Week 10 (Nov 7, 2011)

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

COMP322 - Introduction to C++

STREAMS. (fluxos) Objetivos

Inheritance, Polymorphism, and Interfaces

Inheritance (P1 2006/2007)

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Inheritance. Inheritance

OOP Lab Factory Method, Singleton, and Properties Page 1

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Inheritance (continued) Inheritance

CS Week 13. Jim Williams, PhD

More Relationships Between Classes

All classes in a package can be imported by using only one import statement. If the postcondition of a method is not met, blame its implementer

Class, Variable, Constructor, Object, Method Questions

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Design Patterns: State, Bridge, Visitor

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Handout 9 OO Inheritance.

Conformance. Object-Oriented Programming Spring 2015

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Overview of Java s Support for Polymorphism

Object- Oriented Analysis, Design and Programming

2. (True/False) All methods in an interface must be declared public.

11/1/2011. Chapter Goals

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Chapter 14 Abstract Classes and Interfaces

CLASS DESIGN. Objectives MODULE 4

Chapter 5. Inheritance

CSE331 Winter 2014, Midterm Examination February 12, 2014

Fundamentos de programação

Java Object Oriented Design. CSC207 Fall 2014

CSCI 261 Computer Science II

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Increases Program Structure which results in greater reliability. Polymorphism

Object Oriented Programming 2015/16. Final Exam June 28, 2016

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CS-201 Introduction to Programming with Java

Warm-up: what does this print?

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Lecture 5: Methods CS2301

Java Bytecode (binary file)

Chapter 1 Getting Started

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Object Oriented Programming. Java-Lecture 11 Polymorphism

SSE3052: Embedded Systems Practice

Conversions and Casting

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

Assignment 4: Semantics

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

Transcription:

CHAPTER 9 INTERFACES AND POLYMORPHISM

Using Interfaces for Code Reuse Use interface types to make code more reusable In Chapter 6, we created a DataSet to find the average and maximum of a set of values (numbers) What if we want to find the average and maximum of a set of BankAccount values? 2

File DataSet.java public class DataSet public DataSet() sum = 0; count = 0; maximum = 0; public void add(double x) sum = sum + x; if (count == 0 maximum < x) maximum = x; count++; 3

public double getaverage() if (count == 0) return 0; else return sum / count; public double getmaximum() return maximum; private double sum; private double maximum; private int count; 4

File InputTest.java import javax.swing.joptionpane; public class InputTest public static void main(string[] args) DataSet data = new DataSet(); 5

boolean done = false; while (!done) String input = JOptionPane.showInputDialog ("Enter value, Cancel to quit"); if (input == null) done = true; else double x = Double.parseDouble(input); data.add(x); System.out.println("Average = " + data.getaverage()); System.out.println("Maximum = " + data.getmaximum()); 6

Modifying DataSet for Bank Accounts public class DataSet // modified for BankAccount objects... public void add(bankaccount x) sum = sum + x.getbalance(); if (count==0 maximum.getbalance()<x.getbalance()) maximum = x; count++; public BankAccount getmaximum() return maximum; private double sum; private BankAccount maximum; private int count; 7

Modifying DataSet for Coins public class DataSet // modified for Coin objects... public void add(coin x) sum = sum + x.getvalue(); if (count==0 maximum.getvalue()< x.getvalue()) maximum = x; count++; public Coin getmaximum() return maximum; private double sum; private Coin maximum; private int count; 8

Measurable Interface Suppose various classes could agree on the same method name, getmeasure Then DataSet could call that method: sum = sum + x.getmeasure(); if (count==0 maximum.getmeasure()<x.getmeasure()) maximum = x; Define an interface: public interface Measurable double getmeasure(); 9

Interfaces vs. Classes All methods in an interface are abstract--no implementation All methods in an interface are automatically public An interface doesn't have instance fields 10

Generic DataSet for Measurable Objects public class DataSet... public void add(measurable x) sum = sum + x.getmeasure(); if (count==0 maximum.getmeasure()<x.getmeasure()) maximum = x; count++; public Measurable getmaximum() return maximum; private double sum; private Measurable maximum; private int count; 11

Realizing an Interface Class names interface(s) in implements clause Class supplies definitions of interface methods class ClassName implements Measurable public double getmeasure() implementation additional methods and fields The class must define the methods as public 12

Making BankAccount and Coin Classes Measurable class BankAccount implements Measurable public double getmeasure() return balance; additional methods and fields class Coin implements Measurable public double getmeasure() return value; additional methods and fields 13

File DataSetTest.java public class DataSetTest public static void main(string[] args) DataSet bankdata = new DataSet(); bankdata.add(new BankAccount(0)); bankdata.add(new BankAccount(10000)); bankdata.add(new BankAccount(2000)); Measurable max = bankdata.getmaximum(); System.out.println("Highest balance = " + max.getmeasure()); Continue 14

DataSet coindata = new DataSet(); coindata.add(new Coin(0.25, "quarter")); coindata.add(new Coin(0.1, "dime")); coindata.add(new Coin(0.05, "nickel")); max = coindata.getmaximum(); System.out.println("Highest coin value = " + max.getmeasure()); 15

UML Diagram of DataSet and Related Classes Note that DataSet is decoupled from BankAccount and Coin 16

Syntax 9.1: Defining an Interface public interface InterfaceName method signatures Example: public interface Measurable double getmeasure(); Purpose: To define an interface and its method signatures. The methods are automatically public. 17

Syntax 9. 2: Implementing an Interface public class ClassName implements InterfaceName,... methods instance variables Example: public class BankAccount implements Measurable other methods public double getmeasure() method implementation Purpose: To define a new class that implements the methods of an interface 18

Converting Between Types Can convert from class type to realized interface type: BankAccount account = new BankAccount(10000); Measurable x = account; // OK Same interface type variable can hold reference to Coin x = new Coin(0.1, "dime"); // OK Cannot convert between unrelated types x = new Rectangle(5, 10, 20, 30); // ERROR 19

Casts Add Coin objects to DataSet DataSet coindata = new DataSet(); coindata.add(new Coin(0.25, "quarter")); coindata.add(new Coin(0.1, "dime"));... Get largest Coin with getmaximum method: Measurable max = coindata.getmaximum(); What can you do with it? It's not of type Coin String name = max.getname(); // ERROR You know it's a Coin, but the compiler doesn't. Apply a cast: Coin maxcoin = (Coin)max; String name = maxcoin.getname(); If you are wrong and max isn't a coin, the compiler throws an exception 20

Polymorphism Interface variable holds reference to object of a class that realizes the interface Measurable x; x = new BankAccount(10000); x = new Coin(0.1, "dime"); You can never construct an interface! x = new Measurable(); // ERROR You can call any of the interface methods: double m = x.getmeasure(); // OK Which method is called? 21

Polymorphism Depends on the actual object. If x refers to a bank account, calls BankAccount.getMeasure If x refers to a coin, calls Coin.getMeasure Polymorphism (greek: many shapes): The type of the object determines the method to call Called late binding. Resolved at runtime Different from overloading. Overloading is resolved by the compiler. 22