From Theory to Practice 1 OOP 2006. Overview Reminder – some OOD principles from previous lessons: –Class Inheritance vs. Object Composition –Program.

Slides:



Advertisements
Similar presentations
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Advertisements

From Theory to Practice 2 OOP Overview Performance issues: –Preparing classes for inheritance –Memory management and release of obsolete object.
CS Design Principles Hans Van Vliet, Software Engineering, Principles and Practice, 3 rd edition, John Wiley & Sons, Section Robert C.
CS 211 Inheritance AAA.
AbstractClassesInterfacesPolymorphism1 Abstract Classes, Interfaces, Polymorphism Barb Ericson Georgia Tech April 2010.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
15-Jun-15 Lists in Java Part of the Collections Framework.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
1 Frameworks Part 2. 2 Collections Framework Java API contains library of useful data structures Collections library also serves as framework for adding.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Chapter 3 Introduction to Collections – Stacks Modified
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
CSSE501 Object-Oriented Development. Some OO Design Principles  Majority principles here come from: Design Principles in Java, Bob Tarr.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
Implications of Inheritance COMP206, Geoff Holmes and Bernhard Pfahringer.
More Implications of Inheritance COMP204, Bernhard Pfahringer.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Effective Java, Chapter 4: Classes and Interfaces Last Updated: Fall 2011.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1/20/05A-1 © 2001 T. Horton CS 494 Adv. SW Design and Development A Tasting…. Course 1: Design patterns: Intro, example Course 2: Inheritance, Interfaces,
1 Collections. 2 Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Recitation 7 Godfrey Tan March 21, Administrivia PS6 due Tuesday right after break Final Project descriptions will be handed out Monday after break.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 12 Subtypes and Subclasses.
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 5:Interfaces and Abstract Classes
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 12 Inheritance.
Inheritance and Polymorphism
Design Principles.
CSE 331 Subtyping slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Subtype Polymorphism, Subtyping vs
Lecture 6: Collections.
Part of the Collections Framework
Effective Java: Classes and Interfaces
Hashing in java.util
Presentation transcript:

From Theory to Practice 1 OOP 2006

Overview Reminder – some OOD principles from previous lessons: –Class Inheritance vs. Object Composition –Program to an interface and not an implementation –Modularity The impact of these and other principles is greatly illustrated in the book Effective Java™ by Joshua Bloch –The book contains many rules of thumb for writing a code that is clear, correct, robust and reuseable –Most code samples are taken from / /

Inheritance vs. Composition Reminder The two most common techniques for reusing functionality are inheritance and composition Class Inheritance –Define implementation of one class in terms of another –The internals of the parent are visible to subclass Object Composition –New functionality is obtained by assembling objects –No internal details of objects are visible There are pros and cons for each alternative But, the common rule of thumb is: Favor Composition over Inheritance

Example – Profiling a HashSet Recall some Map API functions: –boolean add(E o) –boolean addAll(Collection c) One implementing class is HashSet. Some constructors of this class are: –HashSet() –HashSet(Collection c) –HashSet (int initialCapacity, float loadFactor) We would like to add a profiling function: –int getAddCount() This function returns the number of attempted element insertions

Using Inheritance import java.util.*; public class InstrumentedHashSet extends HashSet{ // The number of attempted element insertions private int addCount = 0; public InstrumentedHashSet() {} public InstrumentedHashSet(Collection c) { super(c); } public InstrumentedHashSet (int initCap, float loadFactor) { super(initCap, loadFactor); }

public boolean add(Object o) { addCount++; return super.add(o); } public boolean addAll(Collection c) { addCount += c.size(); return super.addAll(c); } public int getAddCount() { return addCount; } Using Inheritance – Handling Counts

What is the result of the following code? Unfortunately the answer is 6 The reason: addAll uses add public static void main(String[] args) { InstrumentedHashSet s = new InstrumentedHashSet(); s.addAll(Arrays.asList(new String[] {"Snap","Crackle","Pop"})); System.out.println(s.getAddCount()); } Using Inheritance – Results

Possible Solutions Do not override addAll : –Problem: depends on implementation details Write addAll using iteration and add. Cons: –Complete re-implementation of the method –Sometimes requires access to private members Another problem with previous solutions: –What if a different add function is add to HashSet ? Another alternative: Composition

import java.util.*; public class InstrumentedSet implements Set { private final Set s; private int addCount = 0; public InstrumentedSet(Set s) { this.s = s; } public boolean add(Object o) { addCount++; return s.add(o); } public boolean addAll(Collection c) { addCount += c.size(); return s.addAll(c); } public int getAddCount() { return addCount; } Using Composition Decorator Pattern

public void clear() { s.clear(); } public boolean contains(Object o) { return s.contains(o); } public boolean isEmpty() { return s.isEmpty(); } public int size() { return s.size(); } public Iterator iterator() { return s.iterator(); } public boolean remove(Object o) { return s.remove(o); } public boolean containsAll(Collection c) { return s.containsAll(c); } Forwarding Methods A forwarding method is a method in the wrapper class which invokes the corresponding method in the contained class and returns the result

public boolean removeAll(Collection c) { return s.removeAll(c); } public boolean retainAll(Collection c) { return s.retainAll(c); } public Object[] toArray() { return s.toArray(); } public Object[] toArray(Object[] a) { return s.toArray(a); } public boolean equals(Object o) { return s.equals(o); } public int hashCode() { return s.hashCode(); } public String toString() { return s.toString(); } } Forwarding Methods - cont

The Pros and Cons of Composition Pros for composition –The underlying Set is completely encapsulated while inheritance breaks encapsulation –Robust, not implementation dependent –Flexible, the profiling functionality works with any kind of set Pros for inheritance –Only methods concerned with new functionality need to be overridden –Natural choice for some ‘is-a’ relations (e.g. Strategy, and Composite patterns) Additional pros and cons in the slides of Lecture 5  Use common sense to weigh the tradeoffs

Program to an interface and not an implementation Reminder from lecture 5: Variables should not be instances of a particular concrete class. Instead commit only to an interface defined by an abstract class. Therefore, if an appropriate interface types exists, parameters, return values, variables and fields should all be declared using interface types. The only reference to an object class is when creating it.

Example Good, uses interface as type: List subscribers = new Vector(); Bad, use class as type Vector subscribers = new Vector(); Using interfaces increase flexibility, such as changing implementation: List subscribers = new ArrayList(); However, this should be done carefully, considering behavioral differences Exceptions to the principle: –Classes without interfaces (such as String ) –Classes with extra functionality (L inkedList )

Building a Good Interface We would like to supply a good interface to the client In Java types the permit multiple implementations can be defined as interfaces or as abstract class –Abstract classes allow implementation of some methods while interfaces do not allow this –A class can implement multiple interfaces while it can inherit only from a single class Should we use Interfaces or Abstract Classes?

Advantages of interfaces –Existing class can be easily retrofitted to implement a new interface Example: Comparable –Allows construction of non-hierarchical type frameworks Example: Integer is both Serializable, Comparable –Enable safe and powerfull functionality enhancements As in the previous example of InstrumentedMap Interfaces vs. Abstract Classes

Advantages of abstract classes –Provides default implementation –It is far easier to evolve an abstract class than it is to evolve an interface: What happens to the implementing classes if we add a new function to the interface? Some advantages can be combined

Skeletal Implementations Skeletal implementations Combine the advantages of interfaces and the ability to provide default implementation in an abstract class These are abstract classes implementing some of the methods defined in the interface Naming convention Abstract –Examples: AbstractCollection, AbstractSet, AbstractList, AbstractMap

Example - AbstractMapEntry Note that this class in not included in the Java Platform library public abstract class AbstractMapEntry implements Map.Entry { // Primitives: must be implemented in the // derived class public abstract K getKey(); public abstract V getValue(); // Entries in modifiable maps must overide // this method public V setValue(V newValue) { throw new UnsupportedOperationException() }

AbstractMapEntry - cont // Implements the general contract of // Map.Entry.hashCode public int hashCode() { return (getKey()==null ? 0 : getKey().hashCode()) ^ (getValue()==null ? 0 : getValue.hashCode());. } Additional implementations here

Rules of Thumb for Interfaces Prefer interfaces to abstract classes Public interfaces should be designed and tested carefully –It is almost impossible to change an interface once it is released If you export a non trivial interface, consider providing a skeletal implementation Use abstract classes only if ease of evolution is more important than flexibility and power

From Requirements to Practicalities (Via Principles) General requirements of a good software system Correct,Clear, Reusable, Robust, Efficient, More? Principles Favor composition over inheritance Write to an interface More… Practicalities Design patterns (e.g. Decorator for composition) Using the Interface mechanism of Java, skeletal implementation Many more …