15
Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke [email protected] Object Oriented Programming Introduction Definition Objected-Oriented Programming is a programming paradigm that uses objects (data structures which have data fields and methods) which interact together within a computer program. Object Oriented Programming Key Ideas Modularity of design Encapsulation of data into Objects Abstraction of an object’s behavior and representation Hierarchical organization of objects with subtypes inheriting behavior and state Polymorphism ability of objects to have multiple forms in different contexts at different times Object Oriented Programming Keep in mind When talking about OOP, keep in mind: Definitions are often blurred, authors/contexts may differ slightly Languages can have some, all, or none OOP features Programs can ignore or utilize some subset of features Non-OOP languages can support some (or all!) OOP features without being “OOP” Debate still going as to “best” practices, how to do OOP, etc. Understanding some concepts requires understanding other concepts Object Oriented Programming Advantages Facilitates modeling of real-world agents & problems Supports modularity & decomposition Clear demarcation of responsibilities and functionality Separates interface (the what) from implementation (the how) Promotes code reuse Bugs, side-effects, etc. can be localized, less and more predictable testing Motivation I Consider the evolution of computer languages Machine Code Assembly Imperative Language Each iteration still forces you to think in terms of a computer’s structure Other Programming language paradigms force models/problems into their paradigm Example: LISP assumes that all problems involve lists Example: C assumes all problems are procedural (algorithmic)

Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke [email protected]

  • Upload
    others

  • View
    16

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Object Oriented Programming

Introduction to Computer Science II

Christopher M. [email protected]

Object Oriented ProgrammingIntroduction

Definition

Objected-Oriented Programming is a programming paradigm that usesobjects (data structures which have data fields and methods) whichinteract together within a computer program.

Object Oriented ProgrammingKey Ideas

I Modularity of design

I Encapsulation of data into Objects

I Abstraction of an object’s behavior and representation

I Hierarchical organization of objects with subtypes inheriting behaviorand state

I Polymorphism ability of objects to have multiple forms in differentcontexts at different times

Object Oriented ProgrammingKeep in mind

When talking about OOP, keep in mind:

I Definitions are often blurred, authors/contexts may differ slightly

I Languages can have some, all, or none OOP features

I Programs can ignore or utilize some subset of features

I Non-OOP languages can support some (or all!) OOP featureswithout being “OOP”

I Debate still going as to “best” practices, how to do OOP, etc.

I Understanding some concepts requires understanding other concepts

Object Oriented ProgrammingAdvantages

I Facilitates modeling of real-world agents & problems

I Supports modularity & decomposition

I Clear demarcation of responsibilities and functionality

I Separates interface (the what) from implementation (the how)

I Promotes code reuse

I Bugs, side-effects, etc. can be localized, less and more predictabletesting

Motivation I

Consider the evolution of computer languages

I Machine Code → Assembly → Imperative Language

I Each iteration still forces you to think in terms of a computer’sstructure

I Other Programming language paradigms force models/problems intotheir paradigm

I Example: LISP assumes that all problems involve lists

I Example: C assumes all problems are procedural (algorithmic)

Page 2: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Motivation II

I In general, problems are forced into a language’s paradigm

I Involves some “translation” or pigeonholing

I Good for domain-specific problems or just number-crunching, bad forgenerality

I Opposite of what it should be: computers should be serving our needs

I Languages should model our world and problems

Contrasting with Other Paradigms

I Most modern programming languages support some OOP features

I Features back-added due to demand or advantages that OOP provides

I OOP vs. Declarative paradigm

I OOP vs. Imperative paradigm

Versus Declarative

Declarative Paradigm

I “Declares” behavior of a program

I Specifies logic of computation, not control flow

I Functional, avoids state (Lisp, Scheme, Haskell)

I Logic programming

I Domain languages: Regular Expressions, HTML, Excel, SQL

I Not necessarily Turing-complete

Versus Imperative

Imperative Paradigm

I Specifies a specific process (algorithm) that changes a program’s state

I Built from one or more procedures (methods, functions)

I Procedural & Structured paradigms (state changes are local orparameterized), not encapsulated

I Examples: FORTRAN, C

History of OOP I

I Paradigms have “evolved” to OOP

I MIT 50s - 60s: LISP “atoms”

I 1960: Sketchpad (first CAD, revolutionary GUI) by Ivan Sutherland,introduced initial concepts

I 1967: Simula 67 by Dahl & Nygaard (bank simulation; agents:tellers, customers, accounts, transactions; physical modeling)

I 1972: Smalltalk by Alan KayI Based on Plato’s Theory of FormsI Allegory of the CaveI “A form is an objective ’blueprint’ of perfection” (an archetype)I No perfect circle, just shadows, representations of it verything has a

quintessence, an archetype, an apotheosis

I 1983: Bjarne Stoustrup develops C++I Inspired to add OOP features to C from Simula

History of OOP II

I First compilers simply translated C++ syntax to pure C

I 1983: Brad Cox & Tom Love develop Objective-CI Inspired to add OOP features to C from Smalltalk

I 1990s: OOP came to dominate programming methodologies(especially due to GUI development)

I Languages updated to include OOP features

I 1995: Java!I 1995 by James Gosling, Sun MicrosystemsI “simple, object-oriented and familiar”I “robust & secure”I “architecture-neutral and portable”I “high performance”I “interpreted, threaded, dynamic”

Page 3: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Continued Refinements I

I Design Patterns - a general reusable solution to a common andreoccurring problem in software design (also called idioms)

I Anti-patterns and “smells”

I Modeling tools (UML – Unified Modeling Language)

I Design-by-contract frameworks

I Integrated Development Environments (IDEs)

I Development of libraries, frameworks

I Development of methodologies, best practices, etc.

Continued Refinements II

Figure : UML Diagram Example

ObjectsAbstract Data Types

I Basis for Objects: Abstract Data Types (ADTs)

I Mathematical model for classes of data structures with similarbehavior or semantics

I Purely theoretical entities

I Generalization applicable to areas other than OOP

I Algebraic structures, AI, algorithms, etc.

I Examples: stacks, queues, maps, strings, and their operations

Objects

Definition

An object is a general entity characterized by the following.

I Identity – An aspect that distinguishes it from other objects

I State – properties (attributes, elements, data, fields)

I Behavior – describes an object’s interface (methods, routines,functions)

Objects IKey Concepts

Message sending

I Objects provide services

I Client code (user) can access these services by sending messages

I Example: a signal to execute one of its methods

I A signal to turn a Light object on() or off()

I Facilitated by an externally available interface

Objects IIKey Concepts

Complex Data Types

I Collection of multiple pieces of information

I Mixed types

I Varying visibility

Page 4: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Objects IIIKey Concepts

Construction

I Objects are constructed rather than assigned

I Construction may be specified through constructors

I Assignment through references

I Contrast with primitive types

Objects IVKey Concepts

Object Design

I General approach: decompose an entity to the point where it issimple enough to implement or a suitable object already exists

I Keep it simple

I Semantics may dictate design

I Avoid the God-Object anti-pattern

Objects VKey Concepts

Examples

I An animal is a general type

I Dogs, Cats, Snakes, Lizards are all animals

I How can we further develop a taxonomy?

I Should the following be incorporated?I Pets?I Gender?

I Strict is-a relationship

I Examples: vehicle, automobile, truck, car, boat plane

4 Main Principles

Object Oriented Programming involves 4 main principles

1. Abstraction

2. Encapsulation

3. Inheritance

4. Polymorphism

Abstraction I

Definition

Abstraction is the mechanism by which objects are given theirrepresentation and implementation details are hidden.

Abstraction is apparent in many areas:

I Application layers (database, middle-tier, front-end)

I System Layers

I Protocol layers (OSI networking model)

Abstraction II

Already familiar with Procedural Abstraction: the implementation of aprocess is codified into a reusable piece of code inside a function.

Example: a square root function may be implemented using variousalgorithms.

I Taylor series

I Babylonian method

I Some other interpolation method

Page 5: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Abstraction III

Example: A sorting function

I Selection sort? Quick sort? Other?

I Temporary space?

I How does it swap?

In the end: who cares?

Procedural abstraction relieves us of the need to worry aboutimplementation details

Abstraction IV

I Abstraction in OOP takes this further: methods implementations areabstracted, but so are the internal representations of the objects

I Objects are defined with a representation similar to is meaning(semantics) while hiding implementation details

I Defines the conceptual boundaries of an object, distinguishingbetween objects

I Allows the client (programmer, user) to deal with objects based ontheir public interface without worrying about details

I It just works!

Abstraction in languages

I Abstraction of objects is achieved through its publicly availableinterface

I Interface specifies how you can use the object

I Specifies which methods may be signaled by client code

I May specify a contract

I In conjunction with inheritance: behavior of subtypes may change, beenhanced, etc.

Abstraction Example 1Date/Time

A date/time stamp object may be defined to represent a particular pointin time (with functionality for formatting, comparing and operating withdurations, intervals, other date/time instances).

How could such an object be represented?

I A collection of individual numbers (year, month, day, etc.)

I A single numerical value (time from a particular epoch)

I ISO 8601-formatted string (ex:2012-05-04T12:20:34.000343+01:00)

Abstraction relieves us of the need to worry about such details

I Representation is internal to the object

I Consistency and changes are handled by the object

I We only interact with its interface

Abstraction Example 2Strings

Most languages support strings, but may use different representations

I A null-terminated character array

I A length-prefixed character array

I Dynamic character array

I ASCII or Unicode?

Representing a string as an object relieves us of the need to worry aboutthese details

I Contrast with procedural language (C): memory management,consistency, expectations must be handled manually

I Instead of worrying about details: just use it!

Example 3

A Graph has vertices (nodes) and edges; may be represented as:

I matrix

I adjacency list

I maps

Page 6: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Encapsulation I

Definition

Encapsulation is a mechanism for restricting access to (some of) anobject’s components and for bundling data and methods operating on thatdata.

Includes:

1. Grouping of data

2. Protection of data

3. Grouping of methods that act on an object’s data

Encapsulation II

I A form of information hiding

I In contrast to abstraction which is implementation hiding

I Includes the aspect of grouping data – modularity

I Protection of data

I Allows restriction to access and control of data

I Allows internal behavior to change, evolve, be fixed without affectingclient code

I Usually breakable (through reflection, exposing in subclasses)

Encapsulation III

I Enables mutator and accessor methodsI Changes are made to be intentionalI Side-effects can be controlled and localizedI Allows validation

I Enables objects to be immutable (predictable, thread-safe)

I Key idea: abstraction allows a user to access essential information,encapsulation hides the data, they compliment each other

EncapsulationBest Practice

I Best practice: make everything private, control access throughgetters/setters

I Objects should not just be data containers

I Any method that acts on an object’s data should be a membermethod

I Do not break encapsulation by placing related functionality elsewhere

Encapsulation IJava Example� �

1 public class BankAccount {

2 private double balance;

3 private double apr;

4 ...

5 // constructors , getters/setters

6 ...

7 public double getMonthlyEarnings () {

8 return this.balance * (this.apr / 12.0);

9 }

10 } � �1. Grouping of data

2. Protection of data

3. Grouping of functionality that acts on that data

Encapsulation IIJava Example

Breaking encapsulation:� �1 public class BankUtils {

2

3 public static double getMonthlyEarnings(

BankAccount acct) {

4 return acct.getBalance () * (acct.getAPR () /

12.0);

5 }

6 } � �

Page 7: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Side-effects

Definition

A function or expression has a side-effect if it modifies some state or hasan observable interaction with calling functions or other parts of theprogram (either globally, to other threads, the outside world, etc.).

Examples:

I A sort method that reorders the original list

I A setter method that modifies an object’s state that can be observedthrough its public interface

I A subroutine used in a logical expression that makes changes to itsparameters

I Any changes to global, static variables, parameters, data I/O, etc.

Why Encapsulation

Beginners question: why can’t everything just be public?

Without Encapsulation:

I Internal state could be modified with impunity

I Everything essentially becomes global

I Difficult to test/control

I Anti-modular

I No way to enforce rules

Save on typing: utilize IDE macros (Eclipse: Source → generategetters/setters)

Inheritance

Definition

Inheritance is the ability to extend the definition of objects; creatingobjects from previously created or defined objects

Most common form: classical inheritance (subclassing)

I subclass/superclass

I derived/base classes

I child/parent classes

Aspects of Inheritance

I Allows us to define a hierarchy of related objects

I Subclasses inherit behavior and/or fields from superclasses

I Subclasses can augment, modify, or change the behavior of methods

I Facilitates code reuse

I Generalized common behavior and/or interface can be defined insuperclasses

I Subclasses provide specialization (more specificity)

I General properties or behavior is specialized into more concreteimplementations

I Super/subclass defines an is-a relationship

InheritanceJava Example

I Bird is a superclass

I All birds move(), but how?

I Ostrich and Robin may be subclasses

I Ostrich may specify a walk() method

I Robin may specify a fly() method

I move() may be overridden in the subclasses to call their respectivemethods

I Subclasses may be referred to as their super class

Java Example� �1 public class Bird {

2 public void move() {

3 System.out.println("Moving somehow ...");

4 }

5 }

67 public class Robin extends Bird {

8 public void fly() {

9 System.out.println("Flying ...");

10 }

11 ...

12 @Override

13 public void move() {

14 this.fly();

15 }

16 }

1718 public class Ostrich extends Bird {

19 public void walk() {

20 System.out.println("Walking ...");

21 }

22 ...

23 @Override

24 public void move() {

25 this.walk();

26 }

27 } � �

Page 8: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Collections Hierarchy I

Collection

Set

HashSet TreeSet

List

ArrayList LinkedList

Figure : Java Collections Library Inheritance structure

Collections Hierarchy II

I A general collection is a data structure that holds stuff

I A set is a collection that holds stuff in an unordered manner; a list isa collection that holds stuff in an ordered manner

I A HashSet is a set that holds stuff in an unordered manner using ahash table

I An ArrayList is a list that holds stuff in an ordered manner using anarray, etc.

Virtual Functions

A virtual function is a function that can be overridden in a subclass.

I C++: all functions are non-virtual by default; can be made virtual byuse of the keyword virtual

I Java: all non-private functions are virtual by default; can be madenon-virtual by use of the keyword final

I static methods can be overridden1

I visibility of methods can be more open, but not decreasedI within a class, access to the superclass’s method is accessible via the

super keyword

1but when static methods are invoked, they should be done so via the class nameanyway

How this works: Dynamic Dispatch

I Upon instantiation, a particular constructor is called

I This creates the object in memory as a virtual table (vtable)

I Object has data in memory, but also references to the code for itsmethods

I When a method is called, the method which the vtable refers to isinvoked

I This process is a run-time mechanism (since methods can be invokedvia a reference to the super class)

How this works: Dynamic DispatchJava Example

� �1 Bird b = new Bird();

2 b.move(); // prints "Moving somehow ..."

3 Robin r = new Robin ();

4 r.move(); // prints "Flying ..."

5 r.fly(); // prints "Flying ..."

6 b = r; // subclass referred to as its superclass

7 b.move(); // prints "Flying ..."

8 //b.fly(); <--compile error

9 b = new Ostrich ();

10 b.move(); // prints "Walking ..." � �

Multiple Inheritance

I An object can inherit from multiple parents, called multipleinheritance

I Example: Musician (inherits from Person, Performer)

I Supported by some languages

I Problematic to implement properly: the diamond problem

I Example: Animal, Dog, Cat, “DogCat”?

I Necessary to establish a mechanism to disambiguate properties

Page 9: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Why Inheritance

I Motivation: Classification & Taxonomy

I Ubiquitous: sheer volume of data requires classification to organize it

I Hierarchical structure is most natural (though not always applicable)

I Fundamental to communication

I Communication requires a common classification/description

Liskov Substitution Principle

The Liskov Substitution Principle states: if S is a (subtype of) T , thenany instance of T should be replaceable by an instance of S withoutaltering any of the desired properties of the program.

I A principle, not a lemma

I I.e. should be the case

I Not guaranteed

I Certainly possible to violate (breakable)

Beware of Pitfalls

I Good practice: avoid the yo-yo anti-pattern (keep relations shallow)

I When in doubt: use composition instead!I Avoid the rectangle problem (or the circle problem):

I Object types should not be mutable to sub/super typesI The is-a relationship (should be) an invariant

I Code Check: take a look at unl.cse.rectangle_problem

Polymorphism

Definition

Polymorphism is the ability to create a variable, method, or an object thathas more than one form (type).

I Derived from Greek: “having multiple forms”

I Inspired by biology (organisms may have different phenotypes:observable traits; genetic, behavioral, or consequence there of)

I Allows more abstract, reusable code

Subtype Polymorphism

I The “default” type of polymorphism

I You can refer to subclass instances as their superclassI Instance’s methods are called dynamically using late-binding

I Because subtypes can provide their own method implementation(overrides),

I There is not enough information at compile time to determine whichmethod to call

I Example: Bird may a move() method; while an Ostrich has a run()method, Robin has a fly() method

I Code Check: let’s take a look at unl.cse.oop.inheritance

I Dynamic Dispatch: compiler is able to create a virtual method table(v-table) with references to the correct method to invoke

Behavioral Subtyping

Behavioral subtyping is a strict type of polymorphism where:

I Liskov Substitution Principle is strictly enforced

I Much stronger form of polymorphism

I Pre- and Post- conditions are defined & enforced (design-by-contract)

I Preconditions cannot be strengthened in subtypes

I Postconditions cannot be weakened in subtypes

I Invariants are guaranteed

I Subtypes must be pure inheritance (no new methods)

I Not generally used in practice

Page 10: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Method Overriding

I Subclass augments, modifies, or provides a completely differentimplementation of a method

I Method has the same name and signature

I May support covariant return types

I Not the same as (operator) overloading (which is done at compiletime)

Ad-hoc Polymorphism I

Ad-hoc Polymorphism covers a wide variety of as-needed polymorphicbehavior.

I Ad-hoc: done as needed for a particular purpose

I On-the-fly polymorphism

Method Overloading I

Method Overloading: several different “versions” of a method may bedefined

I Methods have the same identifier (name)

I In general, have the same return type

I However, must differ in the type or arity (number of) parameters

I Resolution of which method is called is inferred at compile time basedon the arguments at invocation

I May be considered static dispatch

Method Overloading II

Some examples in practice:

I The same name can be used for several versions of an absolute valuefunction (rather than different names for each numeric type)

I C: standard math library has three functions with different names(labs, fabs, abs) for three numeric types; Java: 4 methods withthe same name, different arguments

I Java: String class has 9 valueOf(...) methods to give the Stringvalue of every type

I Java: Integer class has 3 different toString(...) methods (built-in,conversion, base-conversion)

Operator Overloading I

Operator Overloading: built-in operators’ (+, =, etc.) behavior can beredefined depending on its operands

I Some overloading is already built into languages:I String + String may be concatenationI Number + Number may be additionI Number + String may be conversion-addition or

conversion-concatenation

I Some languages allow you to overload an operatorI Could define + to mean union when used with arrays or graphsI Could define + to mean time-addition when used with

date-time/interval types

Operator Overloading II

Should be avoided:

I Of limited use (operator-operand combinations can only have onemeaning)

I All combinations of operands that are used must be defined

I Coding requires defining a function anyway, why not just use thefunction?

I Built-in operators have a clear and understood meaning; when appliedto user defined types or completely redefined, meaning becomesambiguous, unclear, open to interpretation

I Example: what does Array + Array mean?I Concatenation?I Vector addition?I Set union?

Page 11: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Type Coercion I

I When operators are overloaded, rules must be defined for how typesand behaviors are resolved.

I Types are coerced into other types with specific rules so that theoperands become compatible

I Type Coercion: one type is mapped to another compatible type

I Type Promotion: mapping a type to a super-type for compatibility

I Rules may be defined by the language or incompatible types may bedisallowed entirely

I Such type casting may require an explicit instruction by the user

Type Coercion II

Examples:

I Casting numbers to strings in order to concatenate

I Integers are cast to floats in order to add/subtract/multiply

I Floats may be down-casted to integers when the assignment operatoris used

Type Coercion III

General types of conversions:

I Covariant: converting from a specialized type to a generalized type(subclass to superclass, Ostrich to Bird)

I Contravariant: converting from a generalized type to a specializedtype (super to subclass, Bird to Ostrich)

I Invariant: no conversion is possible

Type Coercion IV

Bird

Robin Ostrich

Covariant

Invariant

Contravariant

Figure : Covariance, Contravariance, Invariance

In general, only covariance is “safe” since subtypes define an is-arelationship.

More formally, if A ≤ B, then a transformation f is:

Type Coercion V

I covariant if f(A) ≤ f(B)

I contravariant if f(B) ≤ f(A)

I invariant otherwise

Parametric Polymorphism I

Parametric polymorphism allow us to define methods or classes that havestrong static type-safety, but that can be applied to many different types.

Allows us to write generic code that depends only on some aspect(s) of alltypes that are applicable to the class/method without depending on theactual type.

A method or class is given a generic type, a parameter (parameterized)

The specific type is specified by the client code or deduced at runtime

The parameterized code itself is generic enough that it applies to all types(does not use any type-specific functionality)

Page 12: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Parametric Polymorphism II

Examples:

I A generic “container” class (list or set) can be parameterized to holda specific type (defined at instantiation)

I A generic print method that prints elements in an array or collectionin a tidy format

I A generic getMax() method can be used for all numeric types

I A single, generic sorting method can be defined and used for any typethat is “comparable” in some manner

I Example: a parameterized summation method would need to boundthe types to numerical types

Bounded Parametric Polymorphism

I Some information may be needed by the implementation

I Code needs to know that such objects are numeric types or are“comparable”

I Bounding the parameterized type guarantees a minimum set ofinformation implied by the type

I Bounding the types provides a minimal guarantee of the interfacethey provide (which can then be used!)

Open Recursion

I Objects are defined, but instances are constructed

I An instance may need to refer to its own methods or fields

I No variable reference at compile time

I Special keyword(s) defined (this or self2)

I Bound to a specific object (instance) via late-binding

2Objective-C, Python, Ruby; VB uses Me!

Open RecursionJava keywords

I this can be used inside an object to refer to itself

I super can be used to access methods/variables of a super class

I this(...) can be used to call an object’s constructors

I super(...) can be used to call an object’s superclass’s constructor

Association, Aggregation, Composition I

Association: “a” relation between two classes

I An object knows about another object

I Can call its methods, interact with it

I Most general object–object relationship

Association, Aggregation, Composition II

Aggregation: “the” relation between two classes

I One class “has” another (or usually a collection of another) class

I Usually by reference

I Relationship does not imply ownership

I Other instances may also “have” the object

I Destruction issues

I Example: University – Departments – Faculty

Page 13: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Association, Aggregation, Composition III

Composition: One object owns another

I Upon destruction of owner, owned object(s) are also destroyed

I Should be private: no one else should depend on them

I Composition in Java:I Less important in Java as garbage collection is automaticI If multiple owners, owned objects won’t get destroyed

Association, Aggregation, Composition IV

Composition vs Inheritance

I Inheritance is good when hierarchy is rigid and well-established;design is mature

I Inheritance is fragile as changes up-stream (super classes) will affecteverything downstream

I Composition is more extensible; does not lock you into a hierarchythat would require refactoring

I Composition is more flexible, easier to change and changes have lessof an effect

I Use composition when in doubt

Other IssuesMixins

A mixin is an object that provides functionality to be inherited or reused

I Object’s functionality is mixed in to another object

I Mixin itself is abstract and cannot be instantiated

I Not a form of specialization

I A means to collect functionality into an objectI Java: not directly supported

I Interfaces provide specification, but not behaviorI Abstract classes can provide functionality, but must be inherited and

cannot be multiply inheritedI Preferred solution: composition

Other IssuesDuck Typing

I OOP languages without classes use dynamic typing (JavaScript,Python)

I Methods and properties define a type rather than semantics

I If it walks like a duck (waddle()), talks like a duck (quack()) then itsa Duck

Other IssuesCopy Constructors

I Its often convenient to have a way to create different copies of objects

I Usual to implement a copy constructor: a constructor that takes aninstance of its own class

I Pitfall: the copy should be a deep copy and not just a copy ofreferences

I If not a deep copy, changes to the “shared” resources will be realizedby both copies

SOLID I

SOLID Principles (Features, Martin):

I SRP: Single Responsibility Principle – a class should have only asingle responsibility (i.e. only one potential change in the software’sspecification should be able to affect the specification of the class)

I OCP: Open/Closed Principle – software entities should be open forextension, but closed for modification

I LSP: Liskov Substitution Principle – objects in a program should bereplaceable with instances of their subtypes without altering thecorrectness of that program

I ISP: Interface Segregation Principle – many client-specific interfacesare better than one general-purpose interface

I DIP: Dependency Inversion Principle – one should ?Depend uponAbstractions. Do not depend upon concretions

Page 14: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Summary Example IMaps� �

1 Map <String , Student > m = new HashMap <String ,

Student >();

2 ...

3 String nuid = "12345678";

4 Student s = new Student (...);

5 m.put(nuid , s);

6 ...

7 String someNuid = "87654321";

8 Student joe = m.get(someNuid); � �I Maps are key-value data structures

I Abstraction: get and put methods define how to use this datastructure without worrying about its implementation details

Summary Example IIMaps

I Encapsulation: maps could be implemented using a tree or hashtable;could use open or closed addressing; representation details areirrelevant and hiddent to us

I Inheritance: HashMap is-a Map that uses a hash table (while a TreeMap

is a map that uses a tree)

I Polymorphism: through parametric polymorphism, we can mapspecific types to other specific types

I Java note: a Map is not Collection (see why:http://docs.oracle.com/javase/1.4.2/docs/guide/

collections/designfaq.html#14

Summary Example IIIMaps

Map

AbstractMap

HashMap

LinkedHashMap

TreeMap

Figure : Map data structures in Java Collections library

Software Engineering & Design Books I

Figure : Design Patterns: Elements of Reusable Object-Oriented Software (1994)by Gamma et al.

Software Engineering & Design Books II

Figure : Code Complete (1993) by Steve McConnell

Software Engineering & Design Books III

Figure : The Mythical Man-Month (1975) by Frederick Brooks Jr.

Page 15: Object Oriented Programming - cse.unl.educbourke/ComputerScienceII/... · Object Oriented Programming Introduction to Computer Science II Christopher M. Bourke cbourke@cse.unl.edu

Software Engineering & Design Books IV

Figure : Refactoring: Improving the Design of Existing Code (1999) by MartinFowler