Download presentation
Presentation is loading. Please wait.
Published byAugustine Harmon Modified over 9 years ago
1
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Interfaces
2
Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Topics Abstract Classes Interfaces Final Classes Enumerations
3
Copyright © 2014 by John Wiley & Sons. All rights reserved.3 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.
4
Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Example Employee 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
5
Copyright © 2014 by John Wiley & Sons. All rights reserved.5 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
6
Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Subclass implement inherited abstract method Subclass chose not to implement inherited abstract method. So subclass MUST be declared abstract
7
Copyright © 2014 by John Wiley & Sons. All rights reserved.7 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.
8
Copyright © 2014 by John Wiley & Sons. All rights reserved.8 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.
9
Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Example: creating object Employee: abstract class CommissionEmployee: concrete class OK NOT OK OK
10
Copyright © 2014 by John Wiley & Sons. All rights reserved.10 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.
11
Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Previous example again.. 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(not declared/not inherited) as abstract.
12
Copyright © 2014 by John Wiley & Sons. All rights reserved.12 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.
13
Copyright © 2014 by John Wiley & Sons. All rights reserved.13 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: override getArea that return area of the Rectangle
14
Copyright © 2014 by John Wiley & Sons. All rights reserved.14 Answer public 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
15
Copyright © 2014 by John Wiley & Sons. All rights reserved.15 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
16
Copyright © 2014 by John Wiley & Sons. All rights reserved.16 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
17
Copyright © 2014 by John Wiley & Sons. All rights reserved.17 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
18
Copyright © 2014 by John Wiley & Sons. All rights reserved.18 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
19
Copyright © 2014 by John Wiley & Sons. All rights reserved.19 You can also declare individual methods as final: Class need not be final
20
Copyright © 2014 by John Wiley & Sons. All rights reserved.20 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
21
Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Using Interfaces for Algorithm Reuse Interface types are used to express common operations. Declares a role and associated behavior of a role
22
Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Example1 > Measurable ----------------------------------------- getMeasure() setMeasure(val) Without interface: COIN ----------------------------------------- -Value ----------------------------------------- + getValue() + setValue(val) COUNTRY ----------------------------------------- -area ----------------------------------------- + getArea() + setArea(area) BANK_ACCOUNT ----------------------------------------- -balance ----------------------------------------- + getBalance() + setBalance(balance) Measurable item Behavior associated with measurable item With interface Measurable: COIN ----------------------------------------- -Value ----------------------------------------- getMeasure() setMeasure(val) COUNTRY ----------------------------------------- -area ----------------------------------------- getMeasure() setMeasure(val) BANK_ACCOUNT ----------------------------------------- -balance ----------------------------------------- getMeasure() setMeasure(val) implements If all classes play a common role, You can standardize the behavior related to role using interfaces Interface only declares methods. It does not implement them. Classes implementing interface are Forced to implement all methods declared in interface.
23
Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Example2 Analogy: Standard online application for college –> ROLE: Prospective Student
24
Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Example3 PERSON ------------------------- -name -id ------------------------- +getName() +getId() PERSON ------------------------- -name -id ------------------------- +getName() +getId() PROFESSOR ---------------------------------- -department ---------------------------------- +teachCourse(..) +getSalary() +raiseSalary() +printPayrollStatement() PROFESSOR ---------------------------------- -department ---------------------------------- +teachCourse(..) +getSalary() +raiseSalary() +printPayrollStatement() STUDENT --------------------- -major --------------------- +enroll() STUDENT --------------------- -major --------------------- +enroll() TA --------------------------------------- - courses ----------------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() TA --------------------------------------- - courses ----------------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() Behaviors related to Employee role
25
Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Example3 – solution1 PERSON ------------------------- -name -id ------------------------- +getName() +getId() PERSON ------------------------- -name -id ------------------------- +getName() +getId() PROFESSOR ---------------------------------- -department ---------------------------------- +teachCourse(..) +getSalary() +raiseSalary() +printPayrollStatement() PROFESSOR ---------------------------------- -department ---------------------------------- +teachCourse(..) +getSalary() +raiseSalary() +printPayrollStatement() STUDENT --------------------- -major --------------------- +enroll() STUDENT --------------------- -major --------------------- +enroll() TA --------------------------------------- - courses ----------------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() TA --------------------------------------- - courses ----------------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() Behaviors related to Employee role EMPLOYEE ----------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() EMPLOYEE ----------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() Seems reasonable! But Wait!!!! Employee: - Has no instance variables -Has only methods -Cannot implement those methods So better to implement Employee as an Interface that defines Employee role and functions Only methods + Cant implement methods!
26
Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Example3 Solution: PERSON ------------------------- -name -id ------------------------- +getName() +getId() PERSON ------------------------- -name -id ------------------------- +getName() +getId() PROFESSOR ---------------------------------- -department ---------------------------------- +teachCourse(..) +getSalary() +raiseSalary() +printPayrollStatement() PROFESSOR ---------------------------------- -department ---------------------------------- +teachCourse(..) +getSalary() +raiseSalary() +printPayrollStatement() STUDENT --------------------- -major --------------------- +enroll() STUDENT --------------------- -major --------------------- +enroll() TA --------------------------------------- - courses ----------------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() TA --------------------------------------- - courses ----------------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() Behaviors related to Employee role > EMPLOYEE ----------------------------------- +getSalary() +raiseSalary() +printPayrollStatement() > EMPLOYEE ----------------------------------- +getSalary() +raiseSalary() +printPayrollStatement()
27
Copyright © 2014 by John Wiley & Sons. All rights reserved.27 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
28
Copyright © 2014 by John Wiley & Sons. All rights reserved.28 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
29
Copyright © 2014 by John Wiley & Sons. All rights reserved.29 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; }... }
30
Copyright © 2014 by John Wiley & Sons. All rights reserved.30 Example2 public interface Employee { void RaiseSalary( double d ) ; double GetSalary() ; } 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 > Employee
31
Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Syntax 10.2 Implementing an Interface A class can implement multiple interfaces
32
Copyright © 2014 by John Wiley & Sons. All rights reserved.32 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
33
Copyright © 2014 by John Wiley & Sons. All rights reserved.33 Example Given that Measurable interface and BankAccount class implementing Measurable interface are implemented: OK WRONG! OK WRONG! Cant call methods not in Interface Measure
34
Copyright © 2014 by John Wiley & Sons. All rights reserved.34 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()); }
35
Copyright © 2014 by John Wiley & Sons. All rights reserved.35 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
36
Copyright © 2014 by John Wiley & Sons. All rights reserved.36 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; } public static void main(String args[]) { Measurable account1 = new BankAccount(0); System.out.println("account1.getMeasure() : "+account1.getMeasure()); } BankAccount.java
37
Copyright © 2014 by John Wiley & Sons. All rights reserved.37 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.
38
Copyright © 2014 by John Wiley & Sons. All rights reserved.38 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. E.g. Notepad, Word, PowerPoint, Excel applications print/display
39
Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Question What is wrong with this code? Measurable meas = new Measurable(); System.out.println(meas.getMeasure());
40
Copyright © 2014 by John Wiley & Sons. All rights reserved.40 Answer Answer: Measurable is not a class. You cannot construct objects of type Measurable.
41
Copyright © 2014 by John Wiley & Sons. All rights reserved.41 Question Assuming Country class implements Measurable interface, What is wrong with this code? Measurable meas = new Country("Uruguay", 176220); System.out.println(meas.getName());
42
Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Answer Answer: The variable meas is of type Measurable, and that type has no getName method.
43
Copyright © 2014 by John Wiley & Sons. All rights reserved.43 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
44
Copyright © 2014 by John Wiley & Sons. All rights reserved.44 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?
45
Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Example
46
Copyright © 2014 by John Wiley & Sons. All rights reserved.46 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.
47
Copyright © 2014 by John Wiley & Sons. All rights reserved.47 Example public interface Measurable { double getMeasure(); } public class Coin implements Measurable { double value; //in cents public Coin(double value) { this.value = value; } public double getMeasure() { return value; } public String getName() { if (value==1) return "Penny"; else if(value==5) return "Nickel"; else if(value==10) return "Dime"; else return "Quarter"; } public class MeasurableDemo { public static void main(String args[]) { Coin c1 = new Coin(25); Coin c2 = new Coin(5); Measurable max = larger(c1, c2); Coin maxCoin = (Coin)max; String name = maxCoin.getName(); System.out.println(name); } public static Measurable larger(Measurable obj1, Measurable obj2) { if (obj1.getMeasure() > obj2.getMeasure()) return obj1; return obj2; } }
48
Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Enumeration Types A special data type that enables for a variable to be a set of predefined constants E.g public enum Company { EBAY, PAYPAL, GOOGLE, YAHOO, ATT } public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public enum Currency { PENNY, NICKLE, DIME, QUARTER }
49
Copyright © 2014 by John Wiley & Sons. All rights reserved.49 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.
50
Copyright © 2014 by John Wiley & Sons. All rights reserved.50
51
Copyright © 2014 by John Wiley & Sons. All rights reserved.51 You should always use enums when a variable can only take one out of a small set of possible values. 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.
52
Copyright © 2014 by John Wiley & Sons. All rights reserved.52 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.
53
Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Answer public enum FilingStatus{SINGLE, MARRIED} FilingStatus.java
54
Copyright © 2014 by John Wiley & Sons. All rights reserved.54 1 import java.util.Scanner; 2 /** 3 A tax return of a taxpayer in 2008. 4 */ 5 public class TaxReturn 6 { 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; 11 12 private double income; 13 private FilingStatus status; 14 15 /** 16 Constructs a TaxReturn object for a given income and 17 marital status. 18 @param anIncome the taxpayer income 19 @param aStatus either SINGLE or MARRIED 20 */ 21 public TaxReturn(double anIncome, FilingStatus aStatus) 22 { 23 income = anIncome; 24 status = aStatus; 25 } 26 TaxReturn.java CONTINUED..
55
Copyright © 2014 by John Wiley & Sons. All rights reserved.55 27 public final double getTax() 28 { 29 double tax1 = 0; 30 double tax2 = 0; 31 32 if (status == FilingStatus.SINGLE) 33 { 34 if (income <= RATE1_SINGLE_LIMIT) 35 { 36 tax1 = RATE1 * income; 37 } 38 else 39 { 40 tax1 = RATE1 * RATE1_SINGLE_LIMIT; 41 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT); 42 } 43 } 44 else 45 { 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 } 56 57 return tax1 + tax2; 58 }
56
Copyright © 2014 by John Wiley & Sons. All rights reserved.56 59 60 public static void main(String[] args) 61 { 62 Scanner in = new Scanner(System.in); 63 64 System.out.print("Please enter your income: "); 65 double income = in.nextDouble(); 66 67 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 } 78 79 TaxReturn aTaxReturn = new TaxReturn(income, status); 80 81 System.out.println("Tax: “ + aTaxReturn.getTax()); 83 } 84}
57
Copyright © 2014 by John Wiley & Sons. All rights reserved.57 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. }
58
Copyright © 2014 by John Wiley & Sons. All rights reserved.58 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.
59
Copyright © 2014 by John Wiley & Sons. All rights reserved.59 Example: 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 Inner class
60
Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Inner Classes Assume Student.java is as follows: public class Student{ String name; public Student(String name) { this.name = name; } public String getName() { return this.name; } } 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)); }
61
Copyright © 2014 by John Wiley & Sons. All rights reserved.61 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.
62
Copyright © 2014 by John Wiley & Sons. All rights reserved.62 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
63
Copyright © 2014 by John Wiley & Sons. All rights reserved.63 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");
64
Copyright © 2014 by John Wiley & Sons. All rights reserved.64 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
65
Copyright © 2014 by John Wiley & Sons. All rights reserved.65 Relationships Between Objects Inheritance Implementation (interfaces) Association Dependency Aggregation composition Association Implements/ Realizes Inheritance Dependency Aggregation Composition UML Notation
66
Copyright © 2014 by John Wiley & Sons. All rights reserved.66 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 *
67
Copyright © 2014 by John Wiley & Sons. All rights reserved.67 * *
68
Copyright © 2014 by John Wiley & Sons. All rights reserved.68 Implementation: Class Professor { … ArrayList advisees; … } Class Student { … Professor advisor; … } 1 * Do a few more examples
69
Copyright © 2014 by John Wiley & Sons. All rights reserved.69 Aggregation A special form of association Alternatively referred to as the consists of, is composed of, or has a relationship
70
Copyright © 2014 by John Wiley & Sons. All rights reserved.70 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:
71
Copyright © 2014 by John Wiley & Sons. All rights reserved.71 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
72
Copyright © 2014 by John Wiley & Sons. All rights reserved.72 Implementation: Class Whole { … Arraylist parAList; PartB partB; … } * Class PartA { … Whole whole; … } Class PartB { … Whole whole; … } 1
73
Copyright © 2014 by John Wiley & Sons. All rights reserved.73 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.
74
Copyright © 2014 by John Wiley & Sons. All rights reserved.74 UML Diagram: Book is composed of Chapters
75
Copyright © 2014 by John Wiley & Sons. All rights reserved.75 Implementation Class Book { … ArrayList chapters; … } Class Chapter { … Book book; … } *
76
Copyright © 2014 by John Wiley & Sons. All rights reserved.76 Discuss Project Phase1
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.