Académique Documents
Professionnel Documents
Culture Documents
5/5/18
John Roberts
2
Overview
• Inheritance vs. Composition,
Part 1
• Advantages and
Disadvantages
3
Inheritance vs. Composition (Aggregation) Part 1
5
Overview
• Inheritance vs. Composition,
Part 1
• Advantages and
Disadvantages
6
Abstract classes vs. Interfaces
9
Overview
• Inheritance vs. Composition,
Part 1
• Advantages and
Disadvantages
11
Inheritance vs. Composition (Aggregation) Part 2
class Stack extends Vector {
public Object push( Object item ) { • Stacks can use protected
addElement( item );
members of Vector
return item;
}
public Object peek() { • Stacks can be used wherever
return elementAt( size() - 1 );
Vectors are required as
}
} arguments
12
Inheritance vs. Composition (Aggregation) Part 2
class Stack {
• We can change the private Vector theData;
implementation of Stack from
public Stack() {
Vectors to e.g. array, without theData = new Vector();
any impact on code that uses }
Stacks
public boolean isEmpty() {
return theData.isEmpty();
• Surface area is smaller (don’t }
need to understand Vectors in }
order to understand Stacks)
• Advantages and
Disadvantages
14
Inheritance Advantages
• Substitutability
• Polymorphism is available
15
Inheritance Disadvantages
17
Composition Disadvantages
• No polymorphism
18
Overview
• Inheritance vs. Composition,
Part 1
• Advantages and
Disadvantages
• Very powerful
20
Example: Java Stream Wrappers
• InputStream
• ByteArrayInputStream
• FileInputStream
• PipedInputStream
• FilterInputStream
• BufferedInputStream
• DataInputStream
21
Example: Java Stream Wrappers
FilterInputStream( InputStream in ) {
this.in = in;
}
// etc.
}
22
Example: Java Stream Wrappers
23
Example: Java Stream Wrappers
• InputStream
• FilterInputStream
• BufferedInputStream
• BufferedDataInputStream
• // A lot more
• DataInputStream
• // etc.
• http://developer.classpath.org/doc/java/io/BufferedReader-source.html
public Frog() {
behavior = new TadpoleBehavior();
}
public grow() {
// see if behavior should change
if (behavior.growUp()) {
behavior = new AdultFrogBehavior();
}
26 Inheritance
Dynamic Composition