Object-Oriented Programming



Similar documents
Inheritance in Programming Languages

Glossary of Object Oriented Terms

C++ INTERVIEW QUESTIONS

History OOP languages Year Language 1967 Simula Smalltalk

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Introduction to Object-Oriented Programming

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Java (12 Weeks) Introduction to Java Programming Language

Comp151. Definitions & Declarations

An Incomplete C++ Primer. University of Wyoming MA 5310

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Adapter, Bridge, and Façade

Class 16: Function Parameters and Polymorphism

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

The C Programming Language course syllabus associate level

Basic Programming and PC Skills: Basic Programming and PC Skills:

Ch 7-1. Object-Oriented Programming and Classes

Structural Design Patterns Used in Data Structures Implementation

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Semantic Analysis: Types and Type Checking

AP Computer Science Java Subset

Software Engineering Techniques

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Chapter 5 Functions. Introducing Functions

Goals for This Lecture:

Semester Review. CSC 301, Fall 2015

Curriculum Map. Discipline: Computer Science Course: C++

Practical Session 4 Java Collections

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Moving from CS 61A Scheme to CS 61B Java

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Data Abstraction and Hierarchy

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

C++FA 5.1 PRACTICE MID-TERM EXAM

Lecture 9. Semantic Analysis Scoping and Symbol Table

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Advanced Data Structures

Chapter 3: Restricted Structures Page 1

El Dorado Union High School District Educational Services

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A


iphone SDK Enrolled students will be invited to developer program Login to Program Portal Request a Certificate Download and install the SDK

Android Application Development Course Program

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

Data Structures in the Java API

CS 111 Classes I 1. Software Organization View to this point:

Java EE Web Development Course Program

Java the UML Way: Integrating Object-Oriented Design and Programming

Java Application Developer Certificate Program Competencies

Java Software Structures

Object-Oriented Software Specification in Programming Language Design and Implementation

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Managing Variability in Software Architectures 1 Felix Bachmann*

Object Oriented Design

On the (un)suitability of Java to be the first programming language

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

Functions and Parameter Passing

C++ Crash Kurs. C++ Object-Oriented Programming

Description of Class Mutation Mutation Operators for Java

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

11 November

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Chapter 8: Bags and Sets

Fundamentals of Java Programming

BCS2B02: OOP Concepts and Data Structures Using C++

CSI33 Data Structures

Classes and Pointers: Some Peculiarities (cont d.)

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

The Smalltalk Programming Language. Beatrice Åkerblom

Konzepte objektorientierter Programmierung

Introducing Variance into the Java Programming Language DRAFT

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

CEC225 COURSE COMPACT

Introduction to Programming Block Tutorial C/C++

Java Interview Questions and Answers

Design by Contract beyond class modelling

Symbol Tables. Introduction

Lecture 1: Introduction

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

Introduction to Data Structures

Tutorial on C Language Programming

Domains and Competencies

Chapter 6: Programming Languages

C++ Programming Language

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Visual Basic. murach's TRAINING & REFERENCE

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

CS193j, Stanford Handout #10 OOP 3

Programming Languages CIS 443

Transcription:

Object-Oriented Programming Programming with Data Types to enhance reliability and productivity (through reuse and by facilitating evolution) Object (instance) State (fields) Behavior (methods) Identity Class code describing implementation of an object Data Abstraction Modularity Encapsulation Inheritance Polymorphism CS480 (Prasad) L3OOP 1 CS480 (Prasad) L3OOP 2 Abstraction General: Focus on the meaning Suppress irrelevant implementation details Programming Languages : Assign names to recurring patterns Value : constant identifier Expression : function Statements : procedure Control : loop, switch Value/ops : interface Data Abstraction Focus on the meaning of the operations (behavior), to avoid over-specification. The representation details are confined to only a small set of procedures that create and manipulate data, and all other access is indirectly via only these procedures. Facilitates code evolution. CS480 (Prasad) L3OOP 3 CS480 (Prasad) L3OOP 4

Data Abstraction : Motivation Client/user perspective (Representation Independence) Interested in what a program does, not how. Minimize irrelevant details for clarity. Server/implementer perspective (Information Hiding) Restrict users from making unwarranted assumptions about the implementation. Reserve right to change representation to improve performance, (maintaining behavior). Data Abstraction : Examples Queues (empty, enqueue, dequeue, isempty) array-based implementation linked-list based implementation Tables (empty, insert, lookup, delete, isempty) Sorted array (logarithmic search) Hash-tables (ideal: constant time search) AVL trees (height-balanced) B-Trees (optimized for secondary storage) CS480 (Prasad) L3OOP 5 CS480 (Prasad) L3OOP 6 Modularity Aspect of syntactically grouping related declarations. (E.g., fields and methods of a data type.) Package/class in Java. In OOPLs, a class serves as the basic unit for decomposition and modification. It can be separately compiled. Criteria for Modular Design Supports decomposition for division of labor Supports composition for reuse Supports continuity (incremental updates) for extendibility and smoother evolution Supports understandability Supports protection and isolation CS480 (Prasad) L3OOP 7 CS480 (Prasad) L3OOP 8

ENCAPSULATION Encapsulation Procedural Languages SHARED DATA BET. P & Q proc p; proc q; proc r; /* r can illegally access shared data */ Object-based Languages Shared Data proc p; proc q; proc r; Controlling visibility of names. Enables enforcing data abstraction Conventions are no substitute for enforced constraints. Enables mechanical detection of typos that manifest as illegal accesses. (Cf. problem with global variables) CS480 (Prasad) L3OOP 10 Data Abstraction : Summary Theory : Abstract data types Practice : Information hiding ( server ) Representation independence ( client ) Language : Modularity Encapsulation Inheritance : Subclasses Code reuse derive Colored-Window from Window (also adds fields/methods) Specialization: Customization derive bounded-stack from stack (by overriding/redefining push) Generalization: Factoring Commonality code sharing to minimize duplication update consistency CS480 (Prasad) L3OOP 11 CS480 (Prasad) L3OOP 12

Inheritance/Redefinition : Example import java.awt.color; class Rectangle { int w, h; Rectangle (int ww, int hh) { w = ww; h = hh; int perimeter () { return ( 2*(w + h) ); CS480 (Prasad) L3OOP 13 class ColoredRectangle extends Rectangle { Color c; // inheritance ColoredRectangle (Color cc, int w, int h) { super(w,h); c = cc; class Square extends Rectangle { Square(int w) { super(w,w); int perimeter () { // overriding return ( 4*w ); CS480 (Prasad) L3OOP 14 Open-closed principle A class is closed because it can be compiled, stored in a library, and made available for use by its clients. Stability A class is open because it can be extended by adding new features (operations/fields), or by redefining inherited features. Change Polymorphism (many forms) Integrating objects that exhibit a common behavior and share code. Unifying heterogeneous data. E.g., moving, resizing, minimizing, closing, etc windows and colored windows CS480 (Prasad) L3OOP 15 CS480 (Prasad) L3OOP 16

Polymorphism : Example class Eg { public static void main (String[] args) { Rectangle r = new Rectangle(5,6); System.out.println( r.perimeter() ); r = new ColoredRectangle(Color.red,5,10) ; System.out.println( r.perimeter() ); Polymorphic Variable r r new Rectangle(5,6) new ColoredRectangle(red,5,10) CS480 (Prasad) L3OOP 17 CS480 (Prasad) L3OOP 18 Signature Signature of a procedure is the sequence of types of formal parameters and the result of a function. Signature of a function also includes its return type. + : real x real real push : int x stack stack isempty : stack boolean 0: int CS480 (Prasad) L3OOP 19 Overloading Same name for conceptually related but different operations. E.g., print(5); print( abc ); print(table); E.g., 1 + 2, abc + + xyz Ambiguity resolved on the basis of contextual information ( signature) Scalar Multiplication: 2 * [1,2,3] = [2,4,6] Dot-product: [1,2] * [1,2] = 5 Cross-product: [1,2,0] * [1,2,0] = [0, 0, 0] CS480 (Prasad) L3OOP 20

Binding Associating a method call with the method code to run Resolving ambiguity in the context of overloaded methods Choices for binding time Static: Compile-time Dynamic : Run-time Binding: Static vs Dynamic Static binding (resolved at compile-time) Vector. mul(number) Vector. mul(vector) both mul defined in one class Dynamic binding (resolved at run-time) (Array) Stack. push(5) (List) Stack. push(5) the two pushes defined in different classes CS480 (Prasad) L3OOP 21 CS480 (Prasad) L3OOP 22 Polymorphism and Dynamic Binding Integrating objects that share the same behavior/interface but are implemented differently. Representation independence of clients. (Sharing/Reuse of high-level code.) E.g., searching for an identifier in an array of tables, where each table can potentially have a different implementation. E.g., pushing a value on a stack or a bounded stack. CS480 (Prasad) L3OOP 23 Dynamic Binding : Example Polymorphic data-structure class Eg { public static void main (String[] args) { Rectangle [] rs = { new Rectangle(5,6), new ColoredRectangle(Color.red,1,1), new Square(3) ; for (int i = 0 ; i < rs.length ; i++ ) System.out.println( rs[i].perimeter() ); Polymorphic variable Dynamic Binding CS480 (Prasad) L3OOP 24

Rendition in C++ #include <iostream> using namespace std; class Rectangle { protected: int w, h; public: Rectangle (int ww, int hh) { w = ww; h = hh; virtual int perimeter () { return ( 2*(w + h) ); ; CS480 (Prasad) L3OOP 25 class ColoredRectangle : public Rectangle { private: // inheritance int c; public: ColoredRectangle (int cc, int w, int h) : Rectangle(w,h) { c = cc; ; class Square : public Rectangle { public: Square(int w) : Rectangle(w,w) { int perimeter () { // overriding return ( 4*w ); // protected, not private ; CS480 (Prasad) L3OOP 26 void main (char* argv, int argc) { Rectangle r (5,6); cout << r.perimeter() << endl; ColoredRectangle cr (0,1,1) ; r = cr; // coercion (truncation) cout << r.perimeter() << endl << cr.perimeter() << endl; // inheritance Square s = Square(5); r = s; // NOT polymorphism cout << r.perimeter() << endl; cout << s.perimeter() << endl; // static binding void main (char* argv, int argc) { Rectangle* r = new Rectangle(5,6); cout << r perimeter() << endl; r = new ColoredRectangle(0,1,1) ; cout << r perimeter() << endl; r = new Square(5) ; cout << r perimeter() << endl; // polymorphism and dynamic binding // perimeter() explicitly declared virtual CS480 (Prasad) L3OOP 27 CS480 (Prasad) L3OOP 28

Polymorphic Data Structure and Dynamic Binding in C++ void main (char* argv, int argc) { const RSLEN = 3; // coercion, no dynamic binding Rectangle rs [RSLEN]= { Rectangle(5,6), ColoredRectangle(0,1,1), Square(5) ; for (int i = 0 ; i < RSLEN ; i++ ) cout << rs[i].perimeter() << endl; void main (char* argv, int argc) { const RSLEN = 3; // polymorphism Rectangle* rs [RSLEN]= { new Rectangle(5,6), new ColoredRectangle(0,1,1), new Square(5) ; for (int i = 0 ; i < RSLEN ; i++ ) cout << rs[i] perimeter() << endl; Summarizing :Java vs C++ vs C# Java version uses references to structures Employs polymorphism and dynamic binding C++ version 1, which resembles Java version, uses structures Employs coercion and static binding C++ version 2, which differs from Java version on the surface but simulates Java semantics using references to structures Employs polymorphism and dynamic binding CS480 (Prasad) L3OOP 29 CS480 (Prasad) L3OOP 30 Summarizing :Java vs C++ vs C# As will be seen C# versions combine the syntax of Java and C++ but support only references to structures similarly to Java C# version 1 simulates the Java semantics of polymorphism and dynamic binding by overriding when the parent and child method signatures match C# version 2 enables avoiding overriding and dynamic binding due to coincidental signature match Rendition in C# using System.Drawing; class Rectangle { protected int w, h; public Rectangle (int ww, int hh) { w = ww; h = hh; public virtual int perimeter () { System.Console.WriteLine( "Rectangle.perimeter() called" ); return ( 2*(w + h) ); class ColoredRectangle : Rectangle { protected Color c; // inheritance public ColoredRectangle (Color cc, int w, int h):base(w,h) { c = cc; CS480 (Prasad) L3OOP 31 CS480 (Prasad) L3OOP 32

class Square : Rectangle { public Square(int w): base(w,w) { public override int perimeter () { // overriding System.Console.WriteLine( "Square.perimeter() called" ); return ( 4*w ); class EgA { public static void Main (string[] args) { Rectangle [] rs = { new Rectangle(5,6), new ColoredRectangle(Color.Red,1,1), new Square(2) ; for (int i = 0 ; i < rs.length ; i++ ) System.Console.WriteLine( rs[i].perimeter() ); using System.Drawing; Rendition in C# class Rectangle { protected int w, h; public Rectangle (int ww, int hh) { w = ww; h = hh; public int perimeter () { System.Console.WriteLine( "Rectangle.perimeter() called" ); return ( 2*(w + h) ); class ColoredRectangle : Rectangle { protected Color c; // inheritance public ColoredRectangle (Color cc, int w, int h):base(w,h) { c = cc; CS480 (Prasad) L3OOP 33 CS480 (Prasad) L3OOP 34 class Square : Rectangle { public Square(int w): base(w,w) { public new int perimeter () { // unrelated System.Console.WriteLine( "Square.perimeter() called" ); return ( 4*w ); class EgA { public static void Main (string[] args) { Rectangle [] rs = { new Rectangle(5,6), new ColoredRectangle(Color.Red,1,1), new Square(2) ; for (int i = 0 ; i < rs.length ; i++ ) System.Console.WriteLine( rs[i].perimeter() ); Polymorphism and Dynamic Binding : Examples Viewing various types of files. *.ps, *.ppt, *.html, *.java, etc Determining values of different kinds of expressions. variable, plus-expr, conditional-expr, etc Moving/copying file/directory. Using same bay (interface) to house CD or floppy drive in a laptop. different device drivers Car s interface to a driver. CS480 (Prasad) L3OOP 35 CS480 (Prasad) L3OOP 36

Reuse : Summary Styles : Procedural vs Object-Oriented Inheritance and Polymorphism code sharing / reusing implementation Polymorphism and dynamic binding behavior sharing / reusing higher-level code Accommodating variations in implementation at run-time. Generics / Templates Accommodating variations in type C s Union type and Switch stmt. (Pascal s Variant record and Case stmt.) Explicit dispatching using switch/case Addition of new procs. incremental Not ideal from reuse and modularity view Java s extends for subclass and implements for sub-type. Automatic dispatching using type tags Addition of new impl. (data/ops) incremental Classes in binary form too extensible CS480 (Prasad) L3OOP 37 CS480 (Prasad) L3OOP 38 Styles: Procedural vs Object-Oriented UNION Data 1 Data 2 Data 3 PROCEDURE Proc 1 Proc 2 Proc 3 CLASS Data 1 Proc 1 Data 2 Proc 2 Data 3 Proc 3 CS480 (Prasad) L3OOP 39 Inter-Class Relationships A CarOwner is a Person and has a Car. Composition (Client Relation) ( has a ) Inheritance (Subclass Relation) ( is a ) class CarOwner extends Person { Car c;... The difficulty in choosing between the two relations stems from the fact that when the is view is legitimate, one can always take the has view instead. class CarOwner { Car c; Person p;... CS480 (Prasad) L3OOP 40

Subclass instance ; Client field Person fields CarOwner fields Car CarOwner fields Car Example : OOP Style vs Procedural Style Client Determine the number of elements in a collection. Suppliers Collections : Vector, String, List, Set, Array, etc Procedural Style A client is responsible for invoking appropriate supplier function for determining the size. OOP Style Suppliers are responsible for conforming to the standard interface required for exporting the size functionality to a client. CS480 (Prasad) L3OOP 41 CS480 (Prasad) L3OOP 42 Client in Scheme (define (size C) (cond ( (vector? C) (vector-length C) ) ( (pair? C) (length C) ) ( (string? C) (string-length C) ) ( else size not supported ) ) )) (size (vector 1 2 (+ 1 2))) (size (one two 3)) Suppliers and Client in Java interface Collection { int size(); class myvector extends Vector implements Collection { class mystring extends String implements Collection { public int size() { return length(); class myarray implements Collection { int[] array; public int size() {return array.length; Collection c = new myvector(); c.size(); CS480 (Prasad) L3OOP 43 CS480 (Prasad) L3OOP 44