Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

Abstract Class and Interface
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
COMP 121 Week 2: Interfaces and Polymorphism. Objectives To learn about interfaces To be able to convert between class and interface references To understand.
Interfaces and polymorphism Chapter 9. Interfaces  Used to express operations common to more than one purpose.  Example: You want to find the maximum.
Interfaces and Polymorphism Lesson - 8. Objectives Interfaces Supertype and subtype references Polymorphism Inner classes.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Computer Science A 9: 3/11. Inheritance Today: Inheritance (JC – CCJ ) I have to leave at 11am (but you can stay)
What is an Interface?? An interface is a ‘container’ which contains ONLY abstract methods. public interface Capitalizable { public abstract String outCaps()
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Interfaces and Polymorphism.
Chapter 8 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Chapter 9  Interfaces and Polymorphism 1 Chapter 9 Interfaces and Polymorphism.
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
C++ fundamentals.
Object Oriented Programming, Interfaces, Callbacks Delegates and Events Dr. Mike Spann
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Interfaces and Polymorphism 9.1 Using Interfaces for Code Reuse Defining an Interface implementing an interface 9.2 Converting between Class.
What is an Interface?? An interface is a ‘class’ which contains ONLY abstract methods. public interface Capitalizable { public abstract String outCaps()
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
INTERFACES More OO Concepts. Interface Topics Using an interface Interface details –syntax –restrictions Create your own interface Remember polymorphism.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Interfaces.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Fall 2006Adapted from Java Concepts Companion Slides1 Interfaces and Polymorphism Advanced Programming ICOM 4015 Lecture 10 Reading: Java Concepts Chapter.
CHAPTER 9 INTERFACES AND POLYMORPHISM Chapter Goals: –To learn about interfaces –To be able to convert between supertype and subtype references –To understand.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
CHAPTER 9 INTERFACES AND POLYMORPHISM. CHAPTER GOALS To learn about interfaces To be able to convert between supertype and subtype references To understand.
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced.
Interfaces and Polymorphism CS 162 (Summer 2009).
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
EE2E1. JAVA Programming Lecture 4 Interfaces. Contents Interfaces – introduction Interfaces – introduction Example – generic sorting Example – generic.
Chapter Goals To be able to declare and use interface types
Polymorphism, Abstract Classes & Interfaces
Inheritance and Polymorphism
Interface.
Agenda Warmup AP Exam Review: Litvin A2
Lecture Notes – Interface and Polymorphism (Ch 9-10)
Interfaces and Polymorphism
Chapter 11 – Interfaces and Polymorphism
Section 11.1 Class Variables and Methods
ATS Application Programming: Java Programming
Chapter Three - Implementing Classes
Chapter 11 Interfaces and Polymorphism
Polymorphism, Abstract Classes & Interfaces
Advanced Java Programming
Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces
Presentation transcript:

Chapter 11 – Interfaces and Polymorphism

Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert between class and interface references Understand the concept of polymorphism Understand the concept of polymorphism Understand the purpose of interfaces to decouple classes Understand the purpose of interfaces to decouple classes

Interfaces and Polymorphism Interfaces are important for developing reusable software components Interfaces are important for developing reusable software components Polymorphism is the principal at the heart of this process – a key component of object oriented programming Polymorphism is the principal at the heart of this process – a key component of object oriented programming

Concept #1: Interfaces If you think of a class as a sphere – the interface is the surface If you think of a class as a sphere – the interface is the surface How will code behave (what methods will it define) How will code behave (what methods will it define) Ex. Javadocs are an interface to the underlying class – defines how the class behaves Ex. Javadocs are an interface to the underlying class – defines how the class behaves

Interfaces Java uses interfaces to define a common set of behaviors that varying objects can share Java uses interfaces to define a common set of behaviors that varying objects can share Define an interface that only specifies methods that must be used (not how to use them) Define an interface that only specifies methods that must be used (not how to use them) Create a class that implements this interface – it is signing a contract that it will define all of the methods the interface specifies Create a class that implements this interface – it is signing a contract that it will define all of the methods the interface specifies This contract insures that we can make assumptions about what methods are available (without looking at a Javadoc) This contract insures that we can make assumptions about what methods are available (without looking at a Javadoc)

Interfaces An interface is much like a class in terms of how it is defined except An interface is much like a class in terms of how it is defined except Not instantiable Not instantiable No fields (except constants) No fields (except constants) No body to the methods, only signatures No body to the methods, only signatures Methods are automatically public Methods are automatically public

Example public interface KeyListener { public void keyHit(char c); } Anything that implements this interface must define a method keyHit( ) to handle keyboard entry Anything that implements this interface must define a method keyHit( ) to handle keyboard entry Interfaces only define the minimum methods, you can have as many others as you want Interfaces only define the minimum methods, you can have as many others as you want

Static constant fields Interfaces can have class constant fields Interfaces can have class constant fields Omit public static final – automatically makes fields this way Omit public static final – automatically makes fields this way public interface SwingConstants { int NORTH = 1; int NORTHEAST = 2; int EAST = 3; …}

11.1 Using Interfaces for Code Reuse Use interface types to make code more general Use interface types to make code more general Identify common/essential operations Identify common/essential operations Let’s say there is a class DataSet that keeps track of a running total of real numbers Let’s say there is a class DataSet that keeps track of a running total of real numbers

public class DataSet{ private double sum, maximum; private int count; public void add(double x){ sum = sum + x; if (count == 0 || maximum < x) maximum = x; count++;} public double getMaximum(){ return maximum; } public int getCount(){ return count; }}

Problem: Only works for numbers Problem: Only works for numbers What if we wanted to keep track of BankAccounts? What if we wanted to keep track of BankAccounts?

public class DataSet{ private double sum; private BankAccount maximum; private int count; public void add(BankAccount x) { sum = sum + x.getBalance(); if (count == 0 || maximum.getBalance() < x.getBalance()) || maximum.getBalance() < x.getBalance()) maximum = x; count++;} public BankAccount getMaximum(){ return maximum; } public int getCount(){ return count; }}

What if we want to do the same for Coins? What if we want to do the same for Coins?

public class DataSet{ private double sum; private Coin maximum; private int count; public void add(Coin x) { sum = sum + x.getValue(); if (count == 0 || maximum.Value() < x.getValue()) || maximum.Value() < x.getValue()) maximum = x; count++;} public Coin getMaximum(){ return maximum; } public int getCount(){ return count; }}

The mechanics of analyzing the data is the same in all cases; details of measurement differ The mechanics of analyzing the data is the same in all cases; details of measurement differ We have three classes doing three very similar tasks, but they all contain redundant code We have three classes doing three very similar tasks, but they all contain redundant code Classes could agree on a method getMeasure( ) that obtains the measure to be used in the analysis Classes could agree on a method getMeasure( ) that obtains the measure to be used in the analysis

We can then implement a single reusable DataSet class whose add method looks like this: We can then implement a single reusable DataSet class whose add method looks like this: sum = sum + x.getMeasure(); if (count == 0 || maximum.getMeasure() < x.getMeasure()) { maximum = x; count++; }

Interfaces What type is x? What type is x? We want x to be an type of object that has a getMeasure( ) method We want x to be an type of object that has a getMeasure( ) method Interfaces allow us to ensure that this is the case Interfaces allow us to ensure that this is the case

An interface type is used to specify required operations for a class An interface type is used to specify required operations for a class public interface Measurable { double getMeasure(); }

public class DataSet{ private double sum; private Measurable maximum; private int count; public void add(Measurable x) { sum = sum + x.getMeasure(); if (count == 0 || maximum.getMeasure() < x.getMeasure()) || maximum.getMeasure() < x.getMeasure()) maximum = x; count++;} public Measurable getMaximum(){ return maximum; } public int getCount(){ return count; }}

Interfaces Now DataSet can be used for any class that implements the Measurable interface Now DataSet can be used for any class that implements the Measurable interface To implement an interface, use implements reserved word and implement all methods specified in the interface To implement an interface, use implements reserved word and implement all methods specified in the interface

Defining interfaces public interface InterfaceName { // method signatures // method signatures}

Implements public class ClassName implements Measurable { public double getMeasure() {Implementation } // Additional methods and fields // Additional methods and fields} Note that interface names often end in –able Note that interface names often end in –able Describe an “ability” of the class Describe an “ability” of the class Comparable, Readable, Appendable, Comparable, Readable, Appendable,

Implementing interfaces public class ClassName implements InterfaceName, InterfaceName,... { // methods // instance variables } Can implement multiple interfaces Can implement multiple interfaces

public class BankAccount implements Measurable { public double getMeasure() { return balance; } // Additional methods and fields // Additional methods and fields}

11.2 Converting between classes and interfaces You can convert from a class type to an interface type, provided the class implements the interface You can convert from a class type to an interface type, provided the class implements the interface BankAccount account = new BankAccount(10000); Measurable x = account; // OK Coin dime = new Coin(0.1, "dime"); Measurable x = dime; // Also OK

Cannot convert between unrelated types Measurable x = new Rectangle(5, 10, 20, 30); // ERROR Cannot convert between unrelated types Measurable x = new Rectangle(5, 10, 20, 30); // ERROR Because Rectangle doesn't implement Measurable Because Rectangle doesn't implement Measurable

We know that since Coin implements Measurable, we can assign a Coin object to a Measurable reference variable We know that since Coin implements Measurable, we can assign a Coin object to a Measurable reference variable But what about the other way? Could we always assign a Measurable object to a Coin reference variable? But what about the other way? Could we always assign a Measurable object to a Coin reference variable?

Type casting Add coin objects to DataSet DataSet coinData = new DataSet(); coinData.add(new Coin(0.25, "quarter")); coinData.add(new Coin(0.1, "dime"));... Measurable max = coinData.getMaximum(); Add coin objects to DataSet DataSet coinData = new DataSet(); coinData.add(new Coin(0.25, "quarter")); coinData.add(new Coin(0.1, "dime"));... Measurable max = coinData.getMaximum(); What can you do with it? It's not of type Coin String name = max.getName(); // ERROR What can you do with it? It's not of type Coin String name = max.getName(); // ERROR

You need a cast to convert from an interface type to a class type You need a cast to convert from an interface type to a class type You know it's a coin, but the compiler doesn't. Apply a cast: 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 If you are wrong and max isn't a coin, the compiler throws an exception Compare to casting numbers: Compare to casting numbers: When casting number types you agree to the information loss When casting number types you agree to the information loss When casting object types you agree to the risk of causing an exception When casting object types you agree to the risk of causing an exception

11.3 Polymorphism Interface variable holds reference to object of a class that implements the interface Measurable x; x = new BankAccount(10000); x = new Coin(0.1, "dime"); Interface variable holds reference to object of a class that implements the interface Measurable x; x = new BankAccount(10000); x = new Coin(0.1, "dime"); Note that the object to which x refers doesn't have type Measurable; Note that the object to which x refers doesn't have type Measurable; the type of the object is some class that implements the Measurable interface the type of the object is some class that implements the Measurable interface

Purpose of Polymorphism You can call any of the interface methods: double m = x.getMeasure(); You can call any of the interface methods: double m = x.getMeasure(); Which method is called? Which method is called? Depends on the actual object. Depends on the actual object. If x refers to a bank account, calls BankAccount.getMeasure() If x refers to a bank account, calls BankAccount.getMeasure() If x refers to a coin, calls Coin.getMeasure() If x refers to a coin, calls Coin.getMeasure()

Polymorphism Polymorphism (many shapes): Behavior can vary depending on the actual type of an object Polymorphism (many shapes): Behavior can vary depending on the actual type of an object The property the we can call x.getMeasure() with multiple contexts is an instance of polymorphism The property the we can call x.getMeasure() with multiple contexts is an instance of polymorphism Called late binding: resolved at runtime Called late binding: resolved at runtime Different from overloading; overloading is resolved by the compiler (early binding) Different from overloading; overloading is resolved by the compiler (early binding)