Top Banner
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Interfaces
70
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Interfaces.

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

Interfaces

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

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

Topics

Interfaces Abstract Classes Final Classes Enumerations

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

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.

• Describes a set of methods that a class can be forced to implement.

• It is up to the class implementing the interface to implement ALL the method bodies

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

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

Syntax 10.1 Declaring an Interface

Syntax: public interface InterfaceName {

// method signatures }

Example:Measuarable.java

public interface Measurable{

double getMeasure();}

• You can have more than 1 method declaration (no implementation)• Methods are public by default• Saved as Measuarable.java

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

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

Example1 Coin class implementing Measurable interface:

BankAccount class can implement Measurable interface too!

public class Coin implements Measurable {

public double getMeasure() {

return value; } . . .

}

public class BankAccount implements Measurable {

public double getMeasure() {

return balance; } . . .

}

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

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

Example2

public class TA extends Student implements Employee {

void RaiseSalary( double d ) { // actual code here } double GetSalary() { // actual code here }

}

public class Professor extends Student implements Employee {

void RaiseSalary( double d ) { // actual code here } double GetSalary() { // actual code here }

}

Person

Professor Student

TA<<Interface>> Emplyee

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

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

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

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

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

Example

Given that Measurable interface and BankAccount class implementing Measurable interface are implemented:

OK

WRONG!

OKOK

WRONG!

Cant call methods not inInterface Measure

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

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

Syntax 10.2 Implementing an Interface

A class can implement multiple interfaces

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

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

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() : "+account1.getMeasure()); }

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

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

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

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

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

Answerpublic 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; }

public static void main(String args[]) { Measurable account1 = new BankAccount(0); System.out.println("account1.getMeasure() : "+account1.getMeasure()); }}

BankAccount.java

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

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

Implementing an interface allows a class to become more formal about the behavior it promises to provide.

Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler.

If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

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

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

Another Example

<<interface>> Shapedraw()resize()

Circledraw()resize()

Linedraw()resize()

Rectangledraw()resize()

Squaredraw()resize()

implements

extends

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

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

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 */ }}

Example

Defining static constants in interface is OK

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

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

Interfaces vs Inheritance

Develop interfaces when you have code that processes objects of different classes in a common way.

Interface Inheritance

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.

E.g. Notepad, Word, PowerPoint, Excel applications print/display

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

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

Question

What is wrong with this code?Measurable meas = new Measurable();

System.out.println(meas.getMeasure());

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

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

Answer

Answer: Measurable is not a class. You cannot construct objects of type Measurable.

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

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

Question

Assuming Country class implements Measurable interface, What is wrong with this code? Measurable meas = new Country("Uruguay", 176220);

System.out.println(meas.getName());

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

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

Answer

Answer: The variable meas is of type Measurable, and that type has no getName method.

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

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

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

OK because BankAccount class implements Measurable interface

NOT OK because String class does NOT implement Measurable interface

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

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

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.

Coin? Or BankAccount?

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

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

Example

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

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

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;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);

You need a cast to convert from an interface type to a class type.

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.

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

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

Abstract Classes When you extend an existing class, you have the

choice whether or not to override the methods of the superclass.

Sometimes, it is desirable to force programmers to override a method.

That happens when there is no good default for the superclass, and only the subclass programmer can know how to implement the method properly.

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

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

ExampleEmployee

SalariedEmployee CommissionEmployee

Even if we implement this method, there is no Proper implementation. Only subclasses can provide a suitable implementation (why? There are only either Salaried employees or Commission employees in a company)

So we like to FORCE subclass to override the method.

Right now overriding this method is optional in subclasses

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

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

Solution: Abstract classes and methods

declare the method as an abstract method in superclass (no implementation)

declare class abstract

Now any subclasses are FORCED to implement this abstract method

(OR subclass needs to be declared abstract too!)

Use keyword abstract

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

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

Subclass implement inherited abstract method

Subclass chose not to implement inherited abstract method.

So subclass MUST be declared abstract

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

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

Even if subclass has no own/inherited abstract methods that are not implemented, it can choose to define class abstract.

This is to avoid creating objects from this class.

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

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

Abstract Classes An abstract method has no implementation.

This FORCE the implementers of subclasses to specify concrete implementations of this method.

You cannot construct objects of a abstract class

• you can still have a variable whose type is an abstract class.

• Actual object to which it refers must be an instance of a concrete subclass

A class for which you cannot create objects is called an abstract class.

A class for which you can create objects is sometimes called a concrete class.

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

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

Example: creating objectEmployee: abstract class CommissionEmployee: concrete class

OKNOT OK

OK

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

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

Abstract Classes

Which classes MUST be declared abstract?

1. A class that declares an abstract method

2. A class that inherits an abstract method without overriding it

3. Optionally, if you want, declare classes with no abstract methods as abstract.

• Doing so prevents programmers from creating instances of that class but allows them to create their own subclasses.

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

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

Previous example again..1. A class that declares an

abstract method2. A class that inherits an abstract method without

overriding it

3. Optionally, if you want, declare classes with no abstract methods(not declared/not inherited) as abstract.

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

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

Abstract Classes

Why use abstract classes?

• To FORCE programmers to create subclasses.

• By specifying certain methods as abstract you avoid the trouble of coming up with useless default methods that others might inherit by accident.

abstract classes can have:

• instance variables,

• concrete methods and

• constructors.

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

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

Programming Question

Implement the abstract class Shape:• Instance variables: color [type string]• Constructor: 1-arg constructor that initialize color• Instance method: toString that print “ Shape of color=the

color”• Abstract method: getArea that return area of the shape

Subclass Rectangle:• Instance variables: length, width• Constructor: 3-arg constructor that initaize color,length,width• Instance method: override toString to print instance variable

values• method: overrde getArea that return area of the Rectangle

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

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

Answerpublic abstract class Shape { private String color; public Shape (String color) { this.color = color; } @Override public String toString() { return "Shape of color=" + color; } public abstract double getArea(); }

Shape.java

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

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

public class Rectangle extends Shape { private int length; private int width; public Rectangle(String color, int length, int width) { super(color); this.length = length; this.width = width; } @Override public String toString() { return "Rectangle of length=" + length + " and width=" + width + ",

subclass of " + super.toString(); } @Override public double getArea() { return length*width; }}

Rectangle.java

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

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

public class Triangle extends Shape { private int base; private int height; public Triangle(String color, int base, int height) { super(color); this.base = base; this.height = height; } @Override public String toString() { return "Triangle of base=" + base + " and height=" + height + ", subclass

of " + super.toString(); } @Override public double getArea() { return 0.5*base*height; }}

Triangle.java

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

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

public class TestShape { public static void main(String[] args) { Shape s1 = new Rectangle("red", 4, 5); System.out.println(s1); System.out.println("Area is " + s1.getArea()); Shape s2 = new Triangle("blue", 4, 5); System.out.println(s2); System.out.println("Area is " + s2.getArea()); // Cannot create instance of an abstract class //Shape s3 = new Shape("green"); // Compilation Error!! }}

TestShape.java

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

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

Final Methods and Classes Occasionally, you may want to prevent other programmers from

creating subclasses or from overriding certain methods.

• Opposite of abstract methods

In these situations, you use the final reserved word

E.g. String class in Java library is final:

• i.e. nobody can extend (create subclasses of) the String class

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

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

You can also declare individual methods as final:

Class need not be final

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

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

Common Error

Overriding Methods to Be Less Accessible

If a superclass declares a method to be publicly accessible, you cannot override it to be more private in a subclass.

E.g. superclass: BankAccount

E.g subclass: CheckingAccount

• The compiler does not allow this

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

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

Enumeration Types A special data type that enables for a variable to be a

set of predefined constants

The variable must be equal to one of the predefined values.

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

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

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

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

An enumeration type variable can be null. E.g.

• the status variable in the previous example can actually have three values:

• SINGLE, MARRIED, and null.

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

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

Programming Question

Download TaxReturn.java and TaxCalculator.java from class website and study the code.• The TaxReturn.java uses two int constants to denote SINGLE

and MARRIED status: public static final int SINGLE = 1; public static final int MARRIED = 2;

Declare a new class FilingStatus.java with following enumeration to represent above 2 constants:

public enum FilingStatus{SINGLE, MARRIED}

Modify the TaxReturn class to do the following:• Declare getTax() method final• Modify class to use FilingStatus for status instead of above 2

constants.

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

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

Answer

public enum FilingStatus{SINGLE, MARRIED}

FilingStatus.java

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

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

1 import java.util.Scanner;2 /**3 A tax return of a taxpayer in 2008.4 */5 public class TaxReturn6 { 7 private static final double RATE1 = 0.10;8 private static final double RATE2 = 0.25;9 private static final double RATE1_SINGLE_LIMIT = 32000;10 private static final double RATE1_MARRIED_LIMIT = 64000;1112 private double income;13 private FilingStatus status;1415 /**16 Constructs a TaxReturn object for a given income and 17 marital status.18 @param anIncome the taxpayer income19 @param aStatus either SINGLE or MARRIED20 */ 21 public TaxReturn(double anIncome, FilingStatus aStatus)22 { 23 income = anIncome;24 status = aStatus;25 }26

TaxReturn.java

CONTINUED..

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

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

27 public final double getTax()28 { 29 double tax1 = 0;30 double tax2 = 0;3132 if (status == FilingStatus.SINGLE)33 { 34 if (income <= RATE1_SINGLE_LIMIT)35 {36 tax1 = RATE1 * income;37 }38 else39 {40 tax1 = RATE1 * RATE1_SINGLE_LIMIT;41 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);42 }43 }44 else45 { 46 if (income <= RATE1_MARRIED_LIMIT)47 {48 tax1 = RATE1 * income;49 }50 else 51 {52 tax1 = RATE1 * RATE1_MARRIED_LIMIT;53 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT);54 }55 }5657 return tax1 + tax2;58 }

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

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

59 60 public static void main(String[] args)61 { 62 Scanner in = new Scanner(System.in);6364 System.out.print("Please enter your income: ");65 double income = in.nextDouble();6667 System.out.print("Are you married? (Y/N) ");68 String input = in.next();69 FilingStatus status;70 if (input.equals("Y")) 71 {72 status = FilingStatus.MARRIED;73 }74 else 75 {76 status = FilingStatus.SINGLE;77 }7879 TaxReturn aTaxReturn = new TaxReturn(income, status);8081 System.out.println("Tax: “ + aTaxReturn.getTax());83 }84}

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

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

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.}

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

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

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.

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

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

Example:import java.util.*;

public class Course //OUTER CLASS{

private String name;private ArrayList<Student> enrolledStudents;private GradeBook gradeBook;

public Course(String name) {this.name = name;enrolledStudents = new ArrayList<Student>();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 CLASSprivate HashMap<Student, String> grades;

public GradeBook() {grades = new HashMap<Student, String>();}

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

Inner class

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

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

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));

}}

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

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

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.

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

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

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

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

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

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");

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

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

Answerpublic 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

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

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

Relationships Between Objects

Inheritance Implementation (interfaces) Association Dependency Aggregation composition

Association

Implements/ Realizes

Inheritance

Dependency

Aggregation

Composition

UML Notation

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

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

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 *

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

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

**

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

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

Implementation:

Class Professor{

…ArrayList<Student> advisees;…

}

Class Student{

…Professor

advisor;…

}

1 *

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

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

Aggregation

A special form of association

Alternatively referred to as the • consists of, • is composed of, or • has a relationship

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

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

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

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

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

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:

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

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

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

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

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

Implementation:

Class Whole{

…Arraylist<PartA>

parAList;PartB partB;…

}

*

Class PartA{

…Whole

whole;…

}

Class PartB{

…Whole

whole;…

}

1

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

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

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.

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

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

UML Diagram: Book is composed of Chapters

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

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

Implementation

Class Book{

…ArrayList<Chapter>

chapters;…

}

Class Chapter{

…Book book;…

}

*