52
Object Oriented Programming Chapter 13

Object Oriented Programming

  • Upload
    wirt

  • View
    23

  • Download
    0

Embed Size (px)

DESCRIPTION

Object Oriented Programming. Chapter 13. 13.1: Abstract Data Types. Imperative program design is based on functional decomposition , which systematically refines the problem into smaller and smaller parts until the functions are small enough to represent in primitive language statements. - PowerPoint PPT Presentation

Citation preview

Page 1: Object Oriented Programming

Object Oriented Programming

Chapter 13

Page 2: Object Oriented Programming

13.1: Abstract Data Types

• Imperative program design is based on functional decomposition, which systematically refines the problem into smaller and smaller parts until the functions are small enough to represent in primitive language statements.

• Procedural or functional abstraction: programmers think about the program in terms of function interfaces and functionality (what does it do?)

Page 3: Object Oriented Programming

Data Abstraction

• Extends the idea of procedural abstraction to the data

• Abstract data type: a set of values, and the operations that can be performed on them.

• ADT: provides encapsulation for new data types

Page 4: Object Oriented Programming

Encapsulation - Definition

• Encapsulation is a mechanism which allows logically related constants, types, variables, methods, and so on, to be grouped into a new entity.

• Encapsulation mechanisms limit the scope and visibility of data and functions. Examples: procedure, packages, classes.

Page 5: Object Oriented Programming

History

• Today, OO programming is the preferred way to implement encapsulation.

• Objects aren’t new – Simula 67, Smalltalk-76 and Smalltalk-80.

• Other methods include …

Page 6: Object Oriented Programming

Encapsulation Mechanisms

• C: (13.2-13.3) Header file + implementation file

• Modula 2: Modules – definition and implementation

• Ada: (13.4-13.5) Package – definition and implementation

Page 7: Object Oriented Programming

Abstract Stack Designs/Fig 13.2

• Figure 13.2, 13.3: primitive version of ADT– Encapsulates data and operations for an

integer stack– Linked structure, composed of value/pointer

nodes

• Header + implementation files.

• Can’t generalize to other data types

Page 8: Object Oriented Programming

A Stack Type in CFigure 13.2

stack.hheader file to specify the STACK data type.

Page 9: Object Oriented Programming

Figure 13.3 – Implementation

• Implementation file shows typical stack functions:– empty, newstack, pop, push, top

• Any program that includes the header can declare variables of type STACK and use the functions in the implementation file

Page 10: Object Oriented Programming

Independent Compilation ≠ADT

• Now we have a stack data type and a way to dynamically declare stack variables, but…– There’s no way to prevent the client from bypassing

the defined stack operations to directly access a stack variable; e.g. to search the stack for a particular value

– There’s no way to generalize to other data types

• Better: force stack access to be only through the interface (defined stack functions).

• No inheritance, no encapsulation.

Page 11: Object Oriented Programming

Objectives of Data Abstraction

• Prevent public access to the underlying ADT representation and

• provide a public interface to the ADT through its operations (functions) and prevent any other access; i.e., – provide information hiding by packaging data

and functions together in a unit that provides access only through the defined interface.

Page 12: Object Oriented Programming

Purpose

• The purpose of information hiding is to protect the rest of the program from implementation changes.

• Stable interface

Page 13: Object Oriented Programming

Information Hiding Mechanisms

• Pascal “units”, Modula “modules” and Ada “packages” support these goals.

• Developers are able to prevent direct access to the underlying representation

• These early versions provide encapsulation but lack other desirable characteristics.

Page 14: Object Oriented Programming

Ada Packages – page 313

• Figures 13.4 & 13.5 contain the Ada specification for a generic stack.

• Ada packages are similar to C++/Java class definitions

• Two parts: package definition & package implementation.

• Data and functions can be public or private.

Page 15: Object Oriented Programming

Ada Packages

• Package definition (13.4, p. 313):– Data + function declarations– Private and public (default) specification

• Package implementation (13.4, p 314)– Function implementations

• Package stack_pck is generic; instantiate withpackage int_stack is

new stack_pck(element=>integer);

Page 16: Object Oriented Programming

Problems with Modules, Packages, etc.

• No mechanism for automatic initialization or for finalizing; e.g. open/close, memory alloc.

• No simple way to extend ADT by adding new operations, modifying data characteristics, etc. (No inheritance)

• Some computing paradigms (e.g. GUI-based) were not well modeled by imperative programming style

Page 17: Object Oriented Programming

OO v Imperative Paradigm

• Imperative: Design approach is functional decomposition + limited-feature abstract data types.

• Object oriented: Design approach is object decomposition. Objects include both functions and data.

Page 18: Object Oriented Programming

OO Programming/History

• Simula, an early (mid to late 60’s) OO language, was developed as a simulation language– Included features for modeling the objects

that participated in the simulations

• Smalltalk (early 80’s) was the first language to call itself object-oriented, but concepts came from Simula.

Page 19: Object Oriented Programming

Classes

• Class: a type declaration which encapsulates constants, variables, and functions for manipulating these variables.

• A class is itself an abstract data type and a mechanism for defining ADTs in programs.

• OO languages support encapsulation and information hiding

Page 20: Object Oriented Programming

Section 13.2: The Object-Oriented Model

• Object: an instance (variable) of the class• Instance variables: the local variables of a class.

Also called member variables, fields, …• Methods: functions that operate on objects• Local variables: variables declared in a method• Message: a request to perform an operation on

an object (function call).• Client (of a class): a program or class or method

that uses an object of the class data type

Page 21: Object Oriented Programming

OO Languages Address the Problems That Exist in Modules

• Inheritance– Allows classes to be modified and specialized, which

improves reusability.

• Constructors – Special methods that initialize local instance variables

• Destructors– Some languages have these to finalize objects when

they are no longer needed; e.g. free memory when an object’s scope ends.

Page 22: Object Oriented Programming

Features of OO Languages

• Program Organization

• Visibility and Information Hiding

• Methods and Constructors

• Inheritance

• Polymorphism

Page 23: Object Oriented Programming

OO Program

• An object-oriented program is modeled as a collection of objects that communicate with each other and the user by sending and receiving messages.

• Classic example: GUI application– Objects = buttons, text areas, pull-down

menus, etc.

Page 24: Object Oriented Programming

Class Definition - Java

public class C {private int i, j:// instance

// variablespublic C (<params>)

{<code>} // a constructor

public <type> M (<params>){<code>} // a method

} //end class C

Page 25: Object Oriented Programming

Class Definition – C++

class C {private: int i, j: // instance

// variablespublic:

C::C (<params>){<code>} // a constructor

<type> C::M (<params>){<code>} // a method

} //end class C

Page 26: Object Oriented Programming

Object Declaration and Initialization (Java syntax)

• Declare a variable as an object from the class C: (declaration)

C x;No storage is allocated.

• Declare & initialize a variable x that is an object from class C: (definition)

C x = new C(<arguments>);• A new object is allocated on the heap and

assigned values.

Page 27: Object Oriented Programming

Initialization of an Object in the HeapFigure 7.6

Page 28: Object Oriented Programming

Objects v. Data Structures

• Objects are active, as opposed to the traditional view of data structures as entities that are acted on by functions.

• A message is similar to a function call, but instead of being made by one function to another, a message may be sent from one object to another.

Page 29: Object Oriented Programming

Visibility in OO Languages

• Visibility characterizes the degree of information hiding attached to components (methods, instance variables) of a class.

• Visibility modifiers include– Private: visible only to the current class. – Protected: visible also to a class’s subclasses &, in

Java, to members of other classes in the same package (an unfortunate design decision, according to the authors)

– Public: visible to any client or subclass of the class

Page 30: Object Oriented Programming

Visibility in OO Languages

• Friend functions in C++ can access private members of other classes.– Declared by the class it can access– Used as a stand-alone function

• Usually: class data is private (information hiding) and methods public – forces clients to interface with the class through

its API (interface).– If concrete implementation of data changes,

client classes and subclasses aren’t affected.

Page 31: Object Oriented Programming

Figure 13.8 Stack Class with Visibility Modifiers

public class MyStack{ protected class Node {

public Object val;public Node next;public Node (Object v, Node n){

val = v; next = n;}

}private Node theStack;public MyStack ( ) {theStack = null;}public boolean empty ( ) { return theStack == null;}

public Object top( ) { return theStack.val; }public Object pop( ) {

Object result = theStack.val;theStack = theStack.next:return result;

}public void push(Object v) {

theStack = new Node(v, theStack);}

}

Note the inclusion of an inner class (not the same as a subclass)

The MyStack class is public, the Node class is protected (visible only to subclasses.) Stack data is private, the interface is defined by the functions empty, top, etc.

Page 32: Object Oriented Programming

Constructors & Other Methods

• Note constructors in myStack example.• Constructors are invoked by the new operation;

heap space is allocated and instance variables may be intialized – Node objects are initialized to values,– MyStack objects are initialized to the null pointer

• Constructors are examples of class methods.– Not invoked through a specific object

• push, pop, etc. are examples of instance methods and are invoked through an object.

Page 33: Object Oriented Programming

Using the Stack

• Declare a myStack object as follows: myStack s = new myStack();

• Create a stack with the values 1 and 5:s.push(1);

s.push(2);

s.pop(); // creates garbage

s.push(5);

Page 34: Object Oriented Programming

Creation of a Stack with Two ValuesFigure 13.7

Page 35: Object Oriented Programming

Inheritance: The Class Hierarchy

• Parent or superclass, child or subclass• is-a relation: a member of a subclass is-a

member of the superclass• has-a relation: if class A is a client of class B,

then A has-a B (has-a doesn’t reflect a subclass-superclass relationship)

• Has-a relation between classes sometimes is called an aggregation: C1 is an aggregation of C2 if C1 contains objects of type C2.

Page 36: Object Oriented Programming

Inheritance

• If D is a subclass of C, then D can inherit from C, or acquire attributes (instance variables and methods, including constructors) from it.

• In this case we may refer to C as the base class and D as the derived class.

• In some languages, we say D extends C• Inheritance supports code reuse

Page 37: Object Oriented Programming

Single Inheritance

• Single inheritance limits a class to having only one superclass.

• Single inheritance produces a class hierarchy that can be represented as a tree, with a single root. (Object, in Java)

Page 38: Object Oriented Programming

Multiple Inheritance

• A class may have multiple superclasses.

• Inheritance from more that one parent has good features and bad.– Good: facilitates code reuse by borrowing

characteristics from several parent classes– Bad: confusing. For example, what if two

parent classes have a method with the same name, but different definitions?

Page 39: Object Oriented Programming

Definition

• A language is object-oriented if it supports (1) an encapsulation mechanism with information hiding for defining abstract data types; e.g., classes (2) virtual methods, and (3) inheritance.

• A language is object-based if it allows a program to create any number of instances of an abstract data type.

• You may also see the 3 characteristics listed as (1) classes, (2) polymorphism, and (3) inheritance.

Page 40: Object Oriented Programming

Virtual Methods & Polymorphism

• Informally, a class method is virtual if its subclasses (inheriting classes) can override the implementation in the original class.

• Virtual methods allow OO languages to express polymorphism: the late binding of a call to one of several different implementations in an inheritance hierarchy.

Page 41: Object Oriented Programming

Kinds of Polymorphism

• Parametric polymorphism: a function is defined as a template or generic.– Apply the same operations, in the same way, to different types

• In subtype polymorphism, virtual (polymorphic) functions can also be applied to variables of different types, but the functions themselves behave differently. – Also called inclusion polymorphism because it’s a result of

inheritance & sub-typing.

• Function or operator overloading is sometimes called ad hoc polymorphism.

Page 42: Object Oriented Programming

Templates

• A template defines a family of classes parameterized by one or more types

• Example: collection classes such as lists, stacks, queues, hash tables.– A list can have members from different types:

list of integers, list of strings, etc.

• Templates are also called generics.• Function code is written without any

reference to types.

Page 43: Object Oriented Programming

(sub-type) Polymorphism

• Polymorphic functions have different implementations, depending on the subclass, but all have the same general purpose.

• In a way, polymorphism is a form of information hiding – makes it possible to specify a general kind of behavior, and worry about details later (when subclasses are defined)

Page 44: Object Oriented Programming

Example: Class Hierarchy

Drawable

Triangle Square Ellipse Circle

paint()

The class “Drawable” has several subclasses, each of which has its own version of the paint function. A list (myList) of drawable objects is maintained. To draw each object: for(Drawable obj : myList) // uses the appropriate paint method

obj.paint();

Page 45: Object Oriented Programming

Principle of Substitutability

• A subclass method is substitutable for a parent class method if the subclass’s method performs the same general function– E.g. “draw” – but note that it is the same

function only in an abstract sense.

• This is the essence of polymorphism in OO languages.

Page 46: Object Oriented Programming

Abstract Classes

• Abstraction is an essential feature of computer science. It is a way of filtering out specific details in order to focus on a few important concepts.

• In OO programming, abstract classes support this design mechanism.

Page 47: Object Oriented Programming

Abstract Class

• An abstract class is one that is either declared to be abstract or has one or more abstract methods.

• An abstract method is a method that contains no code beyond its signature.– signature = prototype

• It’s not possible to instantiate an object from an abstract class.

Page 48: Object Oriented Programming

An Abstract Class

• An abstract class can represent an abstract concept.Example:Clite Expression

• Abstract syntax rule:Expression = VariableRef | Value | Binary | Unary

• A Java implementation includes an abstract class Expression with subclasses Variable, Binary, Unary, Value.

Page 49: Object Oriented Programming

Fig. 13 Clite Expression as an Abstract Class

Expression(abstract) display

Variable display

Value Binarydisplay

Unarydisplay

IntValuedisplay

FloatValuedisplay

BoolValuedisplay

CharValuedisplay

Page 50: Object Oriented Programming

Java Interfaces

• Encapsulate a collection of constants and abstract method signatures. An interface may not include either variables, or constructors, or nonabstract methods.

• Declared like an abstract class, except with the word interface. ( public interface Map {…} )

• All methods in an interface are abstract & must be implemented by any class that implements the interface.

Page 51: Object Oriented Programming

Java Interfaces

• A class may implement multiple interfaces, which allows it to appear to be many different types.

• Similar to multiple inheritance• A class can inherit from its parent, but also draw

features from interfaces.– No danger of conflicting method definitions if the parent

and interface have same-named methods; the class is required to re-implement the method

Page 52: Object Oriented Programming

Summary

• OO languages – support encapsulation and data abstraction

through the class mechanism– Provides constructors

• Characterized by inheritance and sub-type polymorphism

• Support run-time type identification (RTTI) which allows an object’s type to be identified at run time