Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.

Similar presentations


Presentation on theme: "Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand."— Presentation transcript:

1 Chapter 9 Interfaces and Polymorphism

2 Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand the concept of polymorphism To appreciate how interfaces can be used to decouple classes Continued…

3 Chapter Goals To learn how to implement helper classes as inner classes To understand how inner classes access variables from the surrounding scope To implement event listeners for timer events

4 Using Interfaces for Code Reuse Use interface types to make code more reusable In Chap. 7, 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? Continued…

5 Using Interfaces for Code Reuse 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; }

6 Using Interfaces for Code Reuse Or 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 Continued…

7 Using Interfaces for Code Reuse 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 Using Interfaces for Code Reuse The mechanics of analyzing the data is the same in all cases; details of measurement differ Classes could agree on a method getMeasure that obtains the measure to be used in the analysis 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++; Continued…

9 Using Interfaces for Code Reuse 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) that the interface type requires public interface Measurable { double getMeasure(); }

10 Interfaces vs. 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 does not have instance fields

11 Generic dataset for Measureable 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; }

12 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 } Continued…

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

14 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 Continued…

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

16 Syntax 11.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 11.2: Implementing an Interface 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

18 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…

19 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…

20 File DataSetTester.java Average balance = 4000.0 Highest balance = 10000.0 Average coin value = 0.13333333333333333 Highest coin value = 0.25 Output:

21 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…

22 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

23 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…

24 Casts 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();

25 Casts 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

26 Polymorphism Interface variable holds reference to object of a class that implements the interface Measurable x ; 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 Continued… x = new BankAccount(10000); x = new Coin(0.1, "dime");

27 Polymorphism You can call any of the interface methods: Which method is called? double m = x.getMeasure();

28 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 (many shapes): Behavior can vary depending on the actual type of an object Continued…

29 Polymorphism Called late binding: resolved at runtime Different from overloading; overloading is resolved by the compiler (early binding)

30 Self Check 5.Why is it impossible to construct a Measurable object? 6.Why can you nevertheless declare a variable whose type is Measurable ? 7.What do overloading and polymorphism have in common? Where do they differ?

31 Answers 5. Measurable is an interface. Interfaces have no fields and no method implementations. 6.That variable never refers to a Measurable object. It refers to an object of some class–a class that implements the Measurable interface. Continued…

32 Answers 7.Both describe a situation where one method name can denote multiple methods. However, overloading is resolved early by the compiler, by looking at the types of the parameter variables. Polymorphism is resolved late, by looking at the type of the implicit parameter object just before making the call.


Download ppt "Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand."

Similar presentations


Ads by Google