Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces."— Presentation transcript:

1 Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Chapter Goals  To be able to declare and use interface types  To appreciate how interfaces can be used to decouple classes  To learn how to implement helper classes as inner classes  To implement event listeners in graphical applications

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Using Interfaces for Algorithm Reuse  Interface types are used to express common operations.  An interface is a collection of method declarations. An interface has no variable declarations or method bodies. It is up to the class implementing the interface to: Implement ALL the method bodies  Describes a set of methods that a class can be forced to implement.

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Using Interfaces for Algorithm Reuse  An interface can be used as a type. Variable and parameter can be of interface types  Interfaces can be used to implement multiple inheritance hierarchies. Read: http://javapapers.com/core-java/why-multiple-inheritance-is-not-supported-in-java/ http://javapapers.com/core-java/why-multiple-inheritance-is-not-supported-in-java/  Methods of an interface are public by default

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Syntax 10.1 Declaring an Interface

6 Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Defining an Interface Type  An interface type is similar to a class.  Differences between classes and interfaces: An interface type does not have instance variables. Measurable m = new Measurable(); //NOT OK All methods in an interface type are abstract o They have a name, parameters, and a return type, but no implementation. All methods in an interface type are automatically public. An interface type has no constructor. o You CANNOT construct objects of an interface type.

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Defining an Interface Type  Using Measurable interface: Implement a reusable average method: public static double average(Measurable[] objects) { double sum = 0; for (Measurable obj : objects) { sum = sum + obj.getMeasure(); } if (objects.length > 0) { return sum / objects.length; } else { return 0; } } This method can be used for objects of any class that conforms to the Measurable type.

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 Implementing an Interface Type  Implementing measurable Interface: Use implements reserved word to indicate that a class implements an interface type: public class BankAccount implements Measurable { … public double getMeasure() { return balance; } } BankAccount objects are instances of the Measurable type: Measurable obj = new BankAccount(); // OK

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Implementing an Interface Type  A variable of type Measurable holds a reference to : an object of some class that implements the Measurable interface. Measurable obj = new BankAccount(); // OK  Country class can also implement the Measurable interface: public class Country implements Measurable { public double getMeasure() { return area; }... }  Use interface types to make code more reusable.

10 Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Implementing an Interface Type  Put the average method in a class - say Data Figure 1 UML Diagram of the Data Class and the Classes that Implement the Measurable Interface  Data class is decoupled from the BankAccount and Country classes.

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Syntax 10.2 Implementing an Interface A class can implement multiple interfaces

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Programming Question  Using interface type vs implementing interface type Implement the Measurable interface Modify Data class to use the Measurable interface and modify BankAccount and Country classes to implement the interface. Test the measurable interface using MeasuarableTester class. Country.java: http://www.users.csbsju.edu/~rdissanayaka/courses/f14/csci160/handouts/ch10/section1/Country.java BankAccount.java: http://www.users.csbsju.edu/~rdissanayaka/courses/f14/csci160/handouts/ch10/section1/BankAccount.java Data.java: http://www.users.csbsju.edu/~rdissanayaka/courses/f14/csci160/handouts/ch10/section1/Data.java MeasurableTester.java: http://www.users.csbsju.edu/~rdissanayaka/courses/f14/csci160/handouts/ch10/section1/MeasurableTester.java

13 Copyright © 2014 by John Wiley & Sons. All rights reserved.13 Answer /** Describes any class whose objects can be measured. */ public interface Measurable { /** Computes the measure of the object. @return the measure */ double getMeasure(); } Measurable.java

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14 Answer public class Data { /** Computes the average of the measures of the given objects. @param objects an array of Measurable objects @return the average of the measures */ public static double average(Measurable[] objects) { double sum = 0; for (Measurable obj : objects) { sum = sum + obj.getMeasure(); } if (objects.length > 0) { return sum / objects.length; } else { return 0; } } Data.java

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Answer public class BankAccount implements Measurable { private double balance; public BankAccount() { balance = 0; } public BankAccount(double initialBalance) { balance = initialBalance; } public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { balance = balance - amount; } public double getBalance() { return balance; } public double getMeasure() { return balance; } BankAccount.java

16 Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Answer Country.java public class Country implements Measurable { private String name; private double area; public Country(String aName, double anArea) { name = aName; area = anArea; } public String getName() { return name; } public double getArea() { return area; } public double getMeasure() { return area; }

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 Answer /** This program demonstrates the measurable BankAccount and Country classes. */ public class MeasurableTester { public static void main(String[] args) { Measurable[] accounts = new Measurable[3]; accounts[0] = new BankAccount(0); accounts[1] = new BankAccount(10000); accounts[2] = new BankAccount(2000); double averageBalance = Data.average(accounts); System.out.println("Average balance: " + averageBalance); System.out.println("Expected: 4000"); Measurable[] countries = new Measurable[3]; countries[0] = new Country("Uruguay", 176220); countries[1] = new Country("Thailand", 513120); countries[2] = new Country("Belgium", 30510); double averageArea = Data.average(countries); System.out.println("Average area: " + averageArea); System.out.println("Expected: 239950"); } MeasurableTester.java

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 Program Run: Average balance: 4000 Expected: 4000 Average area: 239950 Expected: 239950

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Another Example > Shape draw() resize() Circle draw() resize() Line draw() resize() Rectangle draw() resize() Square draw() resize() implements extends

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 public interface Shape { double PI = 3.14; // static and final => upper case void draw(); // automatic public void resize(); // automatic public } public class Rectangle implements Shape { public void draw() {System.out.println ("Rectangle"); } public void resize() { /* do stuff */ } } public class Square extends Rectangle { public void draw() {System.out.println ("Square"); } public void resize() { /* do stuff */ } } Defining static constants in interface is OK

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Interfaces vs Inheritance  Develop interfaces when you have code that processes objects of different classes in a common way. InterfaceInheritance A class can implement more than one interface: public class Country implements Measurable, Named A class can only extend (inherit from) a single superclass. An interface specifies the behavior that an implementing class should supply - no implementation. A superclass provides some implementation that a subclass inherits.

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Question What is wrong with this code? Measurable meas = new Measurable(); System.out.println(meas.getMeasure());

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Answer Answer: Measurable is not a class. You cannot construct objects of type Measurable.

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Question What is wrong with this code? Measurable meas = new Country("Uruguay", 176220); System.out.println(meas.getName());

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Answer Answer: The variable meas is of type Measurable, and that type has no getName method.

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Converting From Classes to Interfaces  You can convert from a class type to an interface type, provided the class implements the interface. BankAccount account = new BankAccount(1000); Measurable meas = account; // OK if BankAccount implements // Measurable interface  A Measurable variable can refer to an object of the Country class because that class also implements the Measurable interface: Country uruguay = new Country("Uruguay", 176220); Measurable meas = uruguay; // Also OK

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Variables of Class and Interface Types Figure 3 An Interface Reference Can Refer to an Object of Any Class that Implements the Interface  Method calls on an interface reference are polymorphic  The appropriate method is determined at run time.

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28 Casting from Interfaces to Classes  Method to return the object with the largest measure: public static Measurable larger( Measurable obj1, Measurable obj) { if (obj1.getMeasure() > obj2.getMeasure()) { return obj1; } else { return obj2; } }  Returns the object with the larger measure, as a Measurable reference. Country uruguay = new Country("Uruguay", 176220); Country thailand = new Country("Thailand", 513120); Measurable max = larger(uruguay, thailand);

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 Casting from Interfaces to Classes  You need a cast to convert from an interface type to a class type.  If reference variable max actually refers to a Country object: Country maxCountry = (Country) max; //cast to class OK String name = maxCountry.getName();  If you are wrong and max doesn't refer to a Country object, the program throws an exception at runtime.

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30 Question Answer: The code fragment prints 20255. The average method calls getMeasure on each object in the array. In the first call, the object is a BankAccount. In the second call, the object is a Country. A different getMeasure method is called in each case. The first call returns the account balance, the second one the area, which are then averaged. What does this code fragment print? Why is this an example of polymorphism? Measurable[] data = { new BankAccount(10000), new Country("Belgium", 30510) }; System.out.println(average(data));

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 The Comparable Interface  Comparable interface is in the standard Java library.  Comparable interface has a single method: public interface Comparable { int compareTo( Object otherObject); }  The call to the method: a.compareTo(b)  The compareTo method returns: a negative number if a should come before b, zero if a and b are the same a positive number if b should come before a.  Implement the Comparable interface so that objects of your class can be compared, E.g. sort method.

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33 Programming Question  Implement the Comparable interface on BankAccount class, so objects can be compared based on account balance.  Modify the main method to create an array named accounts with 3 bank account instances with balances 3000, 2000, and 1000 respectively. Sort the array in the increasing order of balance (use Arrays.sort(accounts)) and print the sorted array.

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 import java.util.Arrays; public class BankAccount implements Comparable { private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount(double balance) { this.balance = balance; lastAssignedNumber++; accountNumber = lastAssignedNumber; } private double getBalance() { return balance; } public String toString() { return "Bank Account No:"+accountNumber+" balance:"+balance; } public int compareTo(Object otherObject) { BankAccount other = (BankAccount) otherObject; if (balance < other.balance) { return -1; } if (balance > other.balance) { return 1; } return 0; } public static void main(String args[]) { BankAccount[] accounts = new BankAccount[3]; accounts[0] = new BankAccount(10000); accounts[1] = new BankAccount(0); accounts[2] = new BankAccount(2000); Arrays.sort(accounts); System.out.println("Sorted accounts based on balance:"); for(BankAccount acct: accounts) System.out.println acct); } BankAccount.java The compareTo method checks whether another object is larger or smaller.

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 Question Can you use the Arrays.sort method to sort an array of String objects? Check the API documentation for the String class.

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36 Answer Yes, you can, because String implements the Comparable interface type.

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37 Question Answer: public static Comparable max(Comparable a,Comparable b) { if (a.compareTo(b) > 0) { return a; } else { return b; } } Write a method max that finds the larger of any two Comparable objects.

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Inner Classes  An inner class X is a class whose declaration is nested within the declaration of another class Y.  The syntax of an inner class declaration is as follows: public class OuterClassX //outer class { // Declare outer class features, as desired... details omitted. // We declare an INNER class wholly within the BODY of the OUTER class. // Note: inner classes are NOT declared to be public - they are only // "visible" as a type to the outer class in which they are declared. class InnerClassY //inner class { // Declare the inner class's features... // details omitted. } // Declare outer class features, as desired... details omitted. }

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Inner Classes  The purpose of declaring an inner class: conceal the fact that the class exists from the application  Invents a private type that only the enclosing outer class knows about. Enclosing outer class can declare variables of type inner class Anywhere else, we cannot! Attempting to do so will produce a “cannot find symbol” compiler error  E.g. Let’s look at a specific example of an inner class called GradeBook, declared within the Course class.

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 Inner Classes  First, we’ll look at the code of the inner class in isolation: class GradeBook { private HashMap grades; public GradeBook() { grades = new HashMap (); } public void setGrade(Student s, String grade) { grades.put(s, grade); } public String getGrade(Student s) { return grades.get(s); }

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41  Next we’ll look at Gradebook class in the context of its enclosing outer class Course: import java.util.*; public class Course //OUTER CLASS { private String name; private ArrayList enrolledStudents; private GradeBook gradeBook; public Course(String name) { this.name = name; enrolledStudents = new ArrayList (); gradeBook = new GradeBook(); } public void assignGrade(Student s, String grade) { gradeBook.setGrade(s, grade); } public String lookUpGrade(Student s) { return gradeBook.getGrade(s); } class GradeBook { //INNER CLASS private HashMap grades; public GradeBook() { grades = new HashMap (); } public void setGrade(Student s, String grade) { grades.put(s, grade); } public String getGrade(Student s) { return grades.get(s); } } // end inner class declaration } // end outer class declaration

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Inner Classes  We may write client code as follows:  Here’s the output: public class MyApp { public static void main(String[] args) { Course c = new Course("MATH 101"); Student s1 = new Student("Fred"); c.assignGrade(s1, "B-"); Student s2 = new Student("Cynthia"); c.assignGrade(s2, "A+"); System.out.println(s1.getName() +" received a grade of " + c.lookUpGrade(s1)); System.out.println(s2.getName() +" received a grade of " + c.lookUpGrade(s2)); }

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Inner Classes  However, if we were to try to reference GradeBook as a type anywhere outside of the Course class:  We get the following compiler error public class MyApp { public static void main(String[] args) { // This won't compile! GradeBook is not known as a type outside of the // Course class boundaries. GradeBook gb = new GradeBook(); // etc.

44 Copyright © 2014 by John Wiley & Sons. All rights reserved.44 Inner Classes  What happens in compilation? When a class containing an inner class definition is compiled, we wind up with separate bytecode files named OuterClass.class and OuterClass$InnerClass.class, respectively E.g. Course.class and Course$GradeBook.class

45 Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Programming Question  Implement the Course class with Gradebook class as a inner class. Implement and test using MyApp class.

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 Relationships Between Objects  Inheritance  Implementation (interfaces)  Association  Dependency  Aggregation  composition Association Implements/ Realizes Inheritance Dependency Aggregation Composition UML Notation

47 Copyright © 2014 by John Wiley & Sons. All rights reserved.47 Association  A relationships between two different classes  E.g. Professor advises Student One-to-many : one professor advises may students. A student is advsed by only one Professor 1 *

48 Copyright © 2014 by John Wiley & Sons. All rights reserved.48 * *

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49  Implementation: Class Professor { … ArrayList advisees; … } Class Student { … Professor advisor; … }

50 Copyright © 2014 by John Wiley & Sons. All rights reserved.50  Rather than simply implementing a Arraylist of courses in CourseCatalog class (which is ok) you can choose to implement it as a Map instead. Map is a list of pairs (like a dictionary): key is the look up key (e.g. course id: String type) value is the associated value (e.g. course object: Course type) This implementation might help you in bigger applications as it allows you to index and find courses in a catalog based on course id. CourseCatalog Course * 1 Class CourseCatalog { … HashMap courses; … } Class Student { … Professor advisor; … }

51 Copyright © 2014 by John Wiley & Sons. All rights reserved.51 Aggregation  A special form of association  Alternatively referred to as the consists of, is composed of, or has a relationship

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52  Like an association: an aggregation is used to represent a relationship between two classes, A and B.  Unlike association: with an aggregation, we’re representing more than mere relationship we’re stating that an object belonging to class 1, known as an aggregate, is composed of, or contains, component objects belonging to class 2

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53  For example, a car is composed of an engine, a transmission, four wheels  so if Car, Engine, Transmission, and Wheel were all classes, then we could form the following aggregations: A Car contains an Engine. A Car contains a Transmission. A Car is composed of many (in this case, four) Wheels.  UML Syntax:

54 Copyright © 2014 by John Wiley & Sons. All rights reserved.54  E.g. University is composed of schools  Notice that we can get by without using aggregation:

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55  We wouldn’t typically say, however, that a Department is composed of many Professors;  instead, we’d probably state that a Department employs many Professors (association relationship).  However, as it turns out, both of these abstractions are ultimately rendered in code in precisely the same way

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56  Implementation: Class Whole { … Arraylist parAList; PartB partB; … } * Class PartA { … Whole whole; … } Class PartB { … Whole whole; … }

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Composition  Composition is a strong form of aggregation  The “parts” cannot exist without the “whole.”  E.g., relationship = “a Book is composed of many Chapters” we could argue that a chapter cannot exist if the book to which it belongs ceases to exist;  E.g. relationship = “a Car is composed of many Wheels”, A wheel can be removed from a car and still serve a useful purpose. Book–Chapter relationship as composition and the Car–Wheel relationship as aggregation.

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58  UML Diagram: Book is composed of Chapters

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59  Implementation Class Book { … ArrayList chapters; … } Class Chapter { … Book book; … }


Download ppt "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces."

Similar presentations


Ads by Google