Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
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.
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)
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.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Chapter 13 Inheritance. An Introduction to Inheritance Inheritance: extend classes by adding methods and fields (variables) Example: Savings account =
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
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.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Unit 031 Interfaces What is an Interface? Interface Declaration Syntax Implementing Interfaces Using Interfaces as Types Interfaces and Inheritance Interfaces.
Java Interfaces Overview Java Interfaces: A Definition.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
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
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
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.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
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.
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.,
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.
Inheritance and Access Control CS 162 (Summer 2009)
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
CHAPTER 9 INTERFACES AND POLYMORPHISM. CHAPTER GOALS To learn about interfaces To be able to convert between supertype and subtype references To understand.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
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.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
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?
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:
1 Interface &Implements. 2 An interface is a classlike construct that contains only constants variables and abstract methods definition. An interface.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 7 : Interfaces King Fahd University of Petroleum & Minerals College of Computer.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
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 15 Abstract Classes and Interfaces
Lecture 3 John Woodward.
Chapter Goals To be able to declare and use interface types
Inheritance and Polymorphism
Lecture Notes – Interface and Polymorphism (Ch 9-10)
Interfaces and Polymorphism
Chapter 11 – Interfaces and Polymorphism
More inheritance, Abstract Classes and Interfaces
Chapter 11 Interfaces and Polymorphism
Advanced Java Programming
Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces
Chapter 11 Inheritance and Encapsulation and Polymorphism
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

Interfaces

Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can be used to decouple classes

Using Interfaces for Code Reuse Use interface types to make code more reusable  Especially between classes that are not related An interface specifies the headings for methods that must be defined for any class that implements the interface

Using Interfaces for Code Reuse: Motivation public class DataSet { // Modified for BankAccount objects 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 = x; count++; } public BankAccount getMaximum() { return maximum; }... }

Using Interfaces for Code Reuse: Motivation (Cont.) In addition, suppose we wanted to find the coin with the highest value among a set of coins. We would need to modify the DataSet class again

public class DataSet { // Modified for Coin objects private double sum; private Coin maximum; private int count; public void add(Coin x) { sum = sum + x.getValue(); if (count == 0 || maximum.getValue() < x.getValue()) maximum = x; count++; } public Coin getMaximum() { return maximum; }... } Using Interfaces for Code Reuse: Motivation (Cont.)

The mechanics of analyzing the data is the same in all cases; details of measurement differ (See for yourself the differences!) In order to remove the differences, we need to have  Classes agree on a method getMeasure() that obtains the measure to be used in the analysis (replacing getValue and getBalance)  Class types of such objects unified (replacing Coin and BankAccount) Here, we can use the Interface as the type!!!! We can 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++; Using Interfaces for Code Reuse: Motivation (Cont.)

What is the type of the variable x? x should refer to any class that has a getMeasure() method In Java, an interface type is used to specify required operations Interface declaration lists all methods (and their signatures) and constant definitions that the interface type requires public interface Measurable { double getMeasure(); } Using Interfaces for Code Reuse (Cont’d)

Defined Constants in Interfaces An interface can contain defined constants in addition to or instead of method headings  Any variables defined in an interface must be public, static, and final  Because this is understood, Java allows these modifiers to be omitted Any class that implements the interface has access to these defined constants

Syntax: Defining an Interface public interface InterfaceName { // constants // method signatures } Example: public interface Measurable { double getMeasure(); } Purpose: To define an interface and its method signatures. The methods are automatically public. Variables are automatically public static final.

Syntax: Implementing an Interface (Cont’d) public class ClassName implements InterfaceName, InterfaceName,... { // methods // instance variables } Example: public class BankAccount implements Measurable { // Other BankAccount methods public double getMeasure() { // Method implementation } Purpose: To define a new class that implements the methods of an interface

We can define the speak() method as part of the Speakable interface. public interface Speakable { public String speak(); // Abstract method } public class Animal implements Speakable { protected String kind; // Cow, pig, cat, etc. public Animal() { } public String speak() { return " "; } Because speak() is no longer defined in Animal, the class Animal should implement the Speakable interface. Syntax: Defining an Interface (Cont’d)

Subclasses of Animal can now implement the Speakable interface in their own distinct ways. public class Cat extends Animal implements Speakable { public Cat() { kind = "cat"; } public String speak() { return "meow"; } public class Cow extends Animal implements Speakable { public Cow() { kind = "cow"; } public String speak() { return "moo"; } Inheritance: A Cat is both an Animal and a Speakable !!! Syntax: Defining an Interface (Cont’d)

Interfaces Versus Classes An interface type is similar to a class, but there are several important differences:  All methods in an interface type are abstract; they don't have an implementation  All methods in an interface type are automatically public  An interface type cannot have instance variables, although they can have constants.

Generic dataset for Measureable Objects 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 = x; count++; } public Measurable getMaximum() { return maximum; }... }

Implementing an Interface Type Use implements keyword to indicate that a class implements an interface type A class can implement more than one interface type  Class must define all the methods that are required by all the interfaces it implements public class BankAccount implements Measurable { public double getMeasure() { return balance; } // Additional methods and fields }

Implementing an Interface Type (Cont’d) Another example: public class Coin implements Measurable { public double getMeasure() { return value; }... }

UML Diagram of Dataset and Related Classes Interfaces can reduce the coupling between classes UML notation:  Interfaces are tagged with a "stereotype" indicator «interface»  A dotted arrow with a triangular tip denotes the "is-a" relationship between a class and an interface  A dotted line with an open v-shaped arrow tip denotes the "uses" relationship or dependency Note that DataSet is decoupled from BankAccount and Coin

UML Diagram of Dataset and Related Classes Figure 1: UML Diagram of Dataset Class and the Classes that Implement the Measurable Interface

Narrowing the scope of the overridden methods in the implementing class! public class Cat extends Animal implements Speakable { public Cat() { kind = "cat"; } String speak() { return "meow"; } public class Cow extends Animal implements Speakable { public Cow() { kind = "cow"; } String speak() { return "moo"; } Compile Error: The scope (access modifier) has been narrowed from public to default! Common Errors

File DataSetTester.java 01: /** 02: This program tests the DataSet class. 03: */ 04: public class DataSetTester 05: { 06: public static void main(String[] args) 07: { 08: DataSet bankData = new DataSet(); 09: 10: bankData.add(new BankAccount(0)); 11: bankData.add(new BankAccount(10000)); 12: bankData.add(new BankAccount(2000)); 13: 14: System.out.println("Average balance = " 15: + bankData.getAverage()); 16: Measurable max = bankData.getMaximum(); 17: System.out.println("Highest balance = " 18: + max.getMeasure()); Continued…

File DataSetTester.java 19: 20: DataSet coinData = new DataSet(); 21: 22: coinData.add(new Coin(0.25, "quarter")); 23: coinData.add(new Coin(0.1, "dime")); 24: coinData.add(new Coin(0.05, "nickel")); 25: 26: System.out.println("Average coin value = " 27: + coinData.getAverage()); 28: max = coinData.getMaximum(); 29: System.out.println("Highest coin value = " 30: + max.getMeasure()); 31: } 32: } Continued…

File DataSetTester.java Average balance = Highest balance = Average coin value = Highest coin value = 0.25 Output:

Converting Between Class and Interface Types 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 Continued…

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

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

Type Casts (Cont’d) 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: If you are wrong and max isn't a coin, the compiler throws an exception Coin maxCoin = (Coin) max; String name = maxCoin.getName();

Type Casts (Cont’d) Difference with casting numbers:  When casting number types you agree to the information loss  When casting object types you agree to that risk of causing an exception