Aggregation and Inheritance Lecture 8.2 Aggregation and Inheritance
Designing with Aggregation and Inheritance Software Design Step 1 Identify the objects. Step 2 Find/design a class for each object. One of the Challenges deciding when to use aggregation and when to use inheritance SupplierClass SuperClass ClientClass SubClass © 2006 Pearson Addison-Wesley. All rights reserved
What is AGGREGATION? public class SomeAggregate { } SomeAggregate private ClassA partA; private ClassB partB; private ClassC partC1; private ClassC partC2; // methods omitted } SomeAggregate ClassA ClassB ClassC © 2006 Pearson Addison-Wesley. All rights reserved
Class Diagram Object Diagram public class SomeAggregate { } private ClassA partA; private ClassB partB; private ClassC partC1; private ClassC partC2; // methods omitted } Class Diagram Object Diagram SomeAggregate ClassA ClassB ClassC :SomeAggregate partA : ClassA partB : ClassB partC1 : ClassC partC2 : ClassC © 2006 Pearson Addison-Wesley. All rights reserved
When to aggregate? One class contains_a other. contains_a An equilateral triangle contains_a vertex. A dog has_a tail. A sandal includes_a sole. A company’s work roster contains_an employee. Cherry pie contains_a cherry pit. contains_a © 2006 Pearson Addison-Wesley. All rights reserved
When to inherit? One class is_a another class is_a An equilateral triangle is_a triangle. A dog is_an animal. A sandal is_a special kind of footware. An hourly employee is_an employee. Cherry pie is_a dessert. is_a Generalizations can be discovered from common attributes. © 2006 Pearson Addison-Wesley. All rights reserved
Create the best relationship from... record button camcorder record button tape recorder lens on/off switch viewfinder tape recorder on/off switch lens camcorder viewfinder © 2006 Pearson Addison-Wesley. All rights reserved
A Dilemma (which is it?) A Camcorder is_a tape recorder. or A Camcorder contains_a tape recorder. Either aggregation or inheritance will work in this case (see next slide). © 2006 Pearson Addison-Wesley. All rights reserved
public class Camcorder { private TapeRecorder rec; ••• //somewhere in the code rec.startRecording(); } public class Camcorder extends TapeRecorder { ••• //somewhere in the code startRecording(); } © 2006 Pearson Addison-Wesley. All rights reserved
java.awt.Container Container is an awt class well suited to inheritance. A Container object is a transparent rectangle. It is useful for grouping other graphical objects into a single unit. An Container subclass can reuse... add and remove setBounds and setLocation getX, getY, getWidth, getHeight, getBackground repaint A Container subclass may want to override... setSize and setBounds setBackground © 2006 Pearson Addison-Wesley. All rights reserved