What is an Interface?? An interface is a ‘container’ which contains ONLY abstract methods. public interface Capitalizable { public abstract String outCaps()

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert.
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)
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.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Polymorphism What is Polymorphism? Taking Advantage of Polymorphism
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
Chapter 10: Inheritance and Polymorphism
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Object Oriented Programming, Interfaces, Callbacks Delegates and Events Dr. Mike Spann
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
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.
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.,
Topic 4 Inheritance.
 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.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
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.
CHAPTER 9 INTERFACES AND POLYMORPHISM. CHAPTER GOALS To learn about interfaces To be able to convert between supertype and subtype references To understand.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
ICOM 4015 Fall 2008 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ICOM 4015: Advanced Programming Lecture 9 Chapter.
Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
CH10 Supplementary Material Prepared by Fatimah Alakeel Oct 2010.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
EE2E1. JAVA Programming Lecture 4 Interfaces. Contents Interfaces – introduction Interfaces – introduction Example – generic sorting Example – generic.
Modern Programming Tools And Techniques-I
Chapter Goals To be able to declare and use interface types
Lecture Notes – Interface and Polymorphism (Ch 9-10)
Interfaces and Polymorphism
Chapter 11 – Interfaces and Polymorphism
Chapter 11 Interfaces and Polymorphism
Presentation transcript:

What is an Interface?? An interface is a ‘container’ which contains ONLY abstract methods. public interface Capitalizable { public abstract String outCaps() ; //returns String representation of object in all capital letters public abstract String outFirstCap(); //returns String representation of object w/ first char in caps public abstract String outNoCaps(); // returns String representation of object in all lowercase }

What is an Interface FOR?? An interface can be used to FORCE a class to provide certain functionality. Suppose we needed to be certain that the class Sentence provided a way to output the object data: in all capitals with first letter capitalized in all lower case

public class Sentence implements Capitalizable { String the_data; public Sentence() { // code for this method } public void addWord(String word) { // code for this method } public int howMany() { // code for this method }

//the class will not compile without these methods!! public String outCaps() { // code for this method } public String outFirstCap(){ // code for this method } public String outNoCaps() { // code for this method } ADDITIONALLY, an object of class Sentence is ALSO an object of type Capitalizable!!!!!!!!!!!

Why might I need to ensure that Sentence offers these methods?? Suppose we wanted to write a program which stored 15 Sentence objects, output them in capital letters, and output the first capital letter in each Sentence;

//Since Sentence implements the Capitalizable interface, Sentence is of type Capitalizable (and has the needed method). If Sentence didn’t implement the Capitalizable interface, this program wouldn’t compile. public static main (String[] args) { Capitalizable [] sobj; sobj = new Capitalizable [16]; // sobj stores Capitalizable references sobj[0] = new Sentence(); // so we can assign a Sentence object! ….. // the other assignments sobj[15] = new Sentence(); for (int index=0; index < 16; index++) System.out.println( “Object at index “ + index + “ is “ + sobj[index].outCaps() ); //the author of this method KNOWS that the outCaps method is there }

Suppose we KNEW that the Sentence class, the Paragraph class, the Word class and the BlockText implemented the Capitalizable interface!! and we wanted to write a program which stored, and manipulated 15 Sentence objects, 15 Paragraph objects, 15 Word object, and 15 BlockText objects

Capitalizable [] textobj; textobj = new Capitalizable [60]; textobj[0] = new Sentence(); textobj[1] = new Paragraph(); textobj[2] = new Word(); textobj[3] = new BlockText(); ….. // other assignments textobj[59] = new BlockText(); // this array can store varying types of objects // all objects can be output in capitals using the same code – // because it is KNOWN that each object has an outCaps method for (int index=0; index < 16; index++) System.out.println( “Object at index “ + index + “ is “ + textobj[index].outCaps() );

You have already seen an interface…. Shape * The Shape interface provides a number of abstract methods, just like any other interface. * Rectangle2D, Line2D, Ellipse2D, RoundRectangle2D, Rectangle2D all implement (realize) the Shape interface. * So a object created from any of these classes is an object of type Shape. * An array declared and instantiated as: Shape [ ] shapelist = new Shape[40]; is capable of storing 40 objects instantiated from any of these classes.

For example: import ……. public class MyShapes extends JComponent{ private Shape [ ] shapelist = new Shape[4]; public MyShapes() { //create the draw shapelist[0] = new Rectangle2D.Double(x,y,width,height); shapelist[1] = new Ellipse2D.Double(x,y,width,height); shapelist[2] = new Line2D.Double(x,y,width,height); shapelist[3] = new RoundRectangle2D.Double(x,y,width,height); }

MyShapes class continued…. public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // draw all the shapes for (int index = 0; index < 4; index ++ ) g2.draw(shapelist[index]); }

The MyShapes class does not make use of the fact that all the objects in the array have many method names in common. This component only uses their common type to allow one array to be used to the all the shapes BUT, since the Shape interface is common to the Line2D.Double class, Rectangle2D.Double class and many other classes, any object that is created from one of these classes is known to provide a common set of methods. We can look at the JAVA API documentation to see what these methods are. The Graphics2D method draw(Shape) knows what these methods are, and uses them -- which is why the parameter must be a Shape.

another use of interfaces … Suppose we had a class named BankAccounts, where an object of this class represented one bank account. (one method of this class is getBalance, which gives the account balance). Now we want to create a class named BADataSet, which can monitor a group BankAccount objects, and keep track of: 1.) total of all bank account balances 2.) largest balance

BADataSet might look like this: public class BADataSet { private double sum; //total of all account balances private BankAccount maximum; //account w/ highest balance private int count; //number of accounts in set public void add ( BankAccount x ){ sum = sum + x. getBalance (); if (count == 0 || maximum. getBalance ()< x. getBalance ()) maximum = x; count++; } public BankAccount getMaximum(){ return maximum; }

Suppose we had a class named Coin, where an object of this class represents one coin. (one method of this class is getTotal, which gives the value of the coin). Now we want to create a class named CDataSet, which can keeps track of a number of Coin objects, keeping track of the total cash and largest coin in a collection of coins.

CDataSet might look like this: public class CDataSet { private double sum; //total of all coin objects private Coin maximum; //coin object with highest value private int count; //number of coin objects in set public void add (Coin x) { sum = sum + x. getTotal (); if (count == 0 || maximum. getTotal ()< x. getTotal ()) maximum = x; count++; } public Coin getMaximum(){ return maximum; }

Gee, both of those classes look quite alike. In fact, except for: * method calls: getBalance().vs. getTotal() * parameter/return types it is the same code. How can we write ONE DataSet class which can handle both types of objects??

Suppose both classes could agree on the same method name, say, getMeasure DataSet could call that method: sum = sum + x.getMeasure(); if (count == 0 || maximum.getMeasure() < x.getMeasure()) maximum = x; Define an interface: public interface Measurable { public abstract double getMeasure(); }

Remember …. when a class ‘implements’ an interface it must provide a full implementation of the abstract methods in the interface So, if both BankAccount and Coin classes ‘implemented’ the measurable interface, we know they have the method getMeasure

class BankAccount implements Measurable{ double balance; //additional variables and methods public double getMeasure(){ return balance; } } class Coin implements Measurable{ double value; //additional variables and methods public double getMeasure(){ return value; } }

public class DataSet { private double sum; private ********* maximum; private int count; public void add(********* x){ sum = sum + x.getMeasure(); if (count == 0 || maximum.getMeasure() < x.getMeasure()) maximum = x; count++; } public ************ getMaximum(){ return maximum; } WE have taken care of the method name, but what data type will work, can’t be BankAccount and can’t be Coin!! }

Remember …. when a class ‘implements’ an interface, objects of that class ARE objects of the interface type as well Eg. A BankAccount object is ALSO a Measurable object So, if both BankAccount and Coin classes ‘implemented’ the Measurable interface, we know they are both objects of class Measurable !

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

// This program tests the DataSet class. 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)); System.out.println("Average balance = " + bankData.getAverage()); Measurable max = bankData.getMaximum(); System.out.println("Highest balance = " + max.getMeasure());

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")); System.out.println("Average coin value = " + coinData.getAverage()); max = coinData.getMaximum(); System.out.println("Highest coin value = " + max.getMeasure()); }

UML Diagram Note that DataSet is decoupled from BankAccount, Coin

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

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(); If the coin class also has a method called ‘getName’ which returns the type of coin as a String…… 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

The instanceof Operator Use instanceof for safe casts: if (max instanceof Coin) { Coin maxCoin = (Coin)max;... }

object instanceof ClassName Example: if (x instanceof Coin) { Coin c = (Coin)x; } Purpose: To return true if the object is an instance of ClassName (or one of its subclasses), false otherwise

Polymorphism Interface variable x holds reference to object of a class that realizes (implements) the interface Measurable x; x = new BankAccount(10000); x = new Coin(0.1, "dime"); You can call any of the interface methods: double m = x.getMeasure(); Which method is called?

Depends on the actual object. If x refers to a bank account, calls BankAccount.getMeasure If x refers to a coin, calls Coin.getMeasure Java can handle this because it supports polymorphism (greek: many shapes) => one reference can refer to different types of objects In the case of a polymorphic object, the actual method which will be called is determined by the type of the object. How does this work?? The JVM uses the actual type of object to determine method to execute at runtime !! (dynamic or late binding) This is called polymorphism. *Different from overloading. Overloading is resolved by the compiler (at compile time).