Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 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.

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Syntax 10.1 Declaring an Interface  Syntax: public interface InterfaceName { // method signatures }  Example: public interface Measurable { double getMeasure(); } You can have more than 1 method declaration (no implementation) Methods are public by default

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4  Coin class implementing Measurable interface:  BankAccount class can implement Measurable interface too!  How about an Employee or Teachable interface for student registration system? public class Coin implements Measurable { public double getMeasure() { return value; }... }

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Defining an Interface Type  You CAN create types of interface type: E.g. Measurable measurable;  An interface type has no constructor.  You CANNOT create objects/instances from an interface E.g. Measurable measurable = new Measurable() //WRONG!  You CAN create objects from a class implementing the interface E.g. Measurable measurable = new Coin() //OK  Interface has NO instance variables  All interface methods are abstract

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

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Programming Question  Implement the Measurable interface (Measurable.java)  Then implement the Measurable interface in BankAccount class  Test BankAccount class: public static void main(String[] args) { Measurable account1 = new BankAccount(0); System.out.println("account1.getMeasure();"); }

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 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

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 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

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

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 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

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 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.

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

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

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

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

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 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

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 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.

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 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);

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 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 uruguay = new Country("Uruguay", 176220); Country thailand = new Country("Thailand", 513120); Measurable max = larger(uruguay, thailand); 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.

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 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. }

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 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.

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 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); }

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24  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

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25 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)); }

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 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.

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 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

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28 Programming Question  Implement the Company (outer) class with following: Inner class: Employee Instance variable: name 1-arg constructor that initialize employee name Instance method getName that return employee name Inner class: Department Instance variable: name 1-arg constructor that initialize department name Instance method getName that return department name Instance method : newStarter: Accepts employee name and department name as parameters Create an employee object and department object Print “employe XXX is a member of department “”YY” main method: Company c = new Company(); c.newStarter("Henry", "IT");

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 Answer public class Company { class Employee { private String name; Employee(String name) { this.name = name; } public String getName() {return name; } } class Department { private String name; Department (String name) { this.name = name; } public String getName() { return name; } } public void newStarter(String name, String department) { Employee emp = new Employee(name); Department dpt = new Department(department); System.out.println(emp.getName() + " is a member of " + dpt.getName()); } public static void main(String[] args) { Company c = new Company(); c.newStarter("Henry", "IT"); } Company.java

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

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

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

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

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

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35  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 An object belonging to class 1(aggregate), is composed of, or contains, component objects belonging to class 2

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36  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:

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37  E.g. University is composed of schools  Notice that we can get by without using aggregation:  Association and aggregation are rendered in code in precisely the same way

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

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 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.

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

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


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

Similar presentations


Ads by Google