The Object Concept. Object-Oriented Programming Spring 2015

Similar documents
The Object Concept. Object-Oriented Programming Spring 2008

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Programming II (CS300)

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Implementing Subprograms

Data Abstraction. Hwansoo Han

An Introduction to C++

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Programming II (CS300)

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

C++ (classes) Hwansoo Han

Introduction to Programming Using Java (98-388)

CS24 Week 3 Lecture 1

CMSC 132: Object-Oriented Programming II

Abstract Data Types and Encapsulation Concepts

COEN244: Class & function templates

CMSC 132: Object-Oriented Programming II

Common Misunderstandings from Exam 1 Material

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

G Programming Languages - Fall 2012

CPS 506 Comparative Programming Languages. Programming Language

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Object-Oriented Programming

C++ (Non for C Programmer) (BT307) 40 Hours

Storage. Outline. Variables and Updating. Composite Variables. Storables Lifetime : Programming Languages. Course slides - Storage

Programming, numerics and optimization

Chapter 11. Abstract Data Types and Encapsulation Concepts

Lecture 23: Object Lifetime and Garbage Collection

Abstract data types &

Abstract Data Types & Object-Oriented Programming

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

VALLIAMMAI ENGINEERING COLLEGE

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Java Object Oriented Design. CSC207 Fall 2014

G Programming Languages - Fall 2012

OBJECT ORIENTED PROGRAMMING USING C++

Chapter 11. Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

THE CONCEPT OF OBJECT

Data Structures (list, dictionary, tuples, sets, strings)

Objects Managing a Resource

Special Member Functions

Implications of Substitution עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

CS304 Object Oriented Programming Final Term

CMSC 4023 Chapter 11

Chapter 10 :: Data Abstraction and Object Orientation

Introduction to Programming

COSC252: Programming Languages: Abstraction and OOP. Jeremy Bolton, PhD Asst Teaching Professor. Copyright 2015 Pearson. All rights reserved.

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Chapter 6 Introduction to Defining Classes

The Dynamic Typing Interlude

END TERM EXAMINATION

Creating an object Instance variables

Instantiation of Template class

Introduction To C#.NET

Inheritance, and Polymorphism.

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CA341 - Comparative Programming Languages

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Lecture 7: Data Abstractions

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

Concepts of Object Oriented Programming

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

STRUCTURING OF PROGRAM

Memory management COSC346

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

(7 2) Classes: A Deeper Look D & D Chapter 9. Instructor - Andrew S. O Fallon CptS 122 (February 22, 2019) Washington State University

Storage. Outline. Variables and updating. Copy vs. Ref semantics Lifetime. Dangling References Garbage collection

CS1004: Intro to CS in Java, Spring 2005

Chapter 9 :: Data Abstraction and Object Orientation

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000

Chapter 10 Introduction to Classes

Encapsulation in C++

Introduce C# as Object Oriented programming language. Explain, tokens,

Absolute C++ Walter Savitch

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Object-oriented Programming. Object-oriented Programming

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

2 ADT Programming User-defined abstract data types

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

What are the characteristics of Object Oriented programming language?

PROFESSOR: DR.JALILI BY: MAHDI ESHAGHI

Object Oriented Paradigm

Announcements/Follow-ups

1. Software Systems Complexity, OO Paradigm, UML

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Polymorphism Part 1 1

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lecture Notes on Programming Languages

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Transcription:

The Object Concept Object-Oriented Programming 236703 Spring 2015

Identity The Basics Of Objects It must be possible to determine whether two objects are the same. State Set of characteristics Behavior Set of operations??? Object = ID + State + Behavior 2

Where Do Objects Come From? The problem space: o Employee o Salary o Date The program space: o Linked list o File o String Dilbert

Some Object Examples The complex number e 3+2I Characteristics: Real part, Imaginary part,... Operations: add, multiply,... The list (13, hello, true) Characteristics: Elements, length,... Operations: Add, remove, print, iterate over, sort,... The vehicle My old GMC, license plate #313-430 Characteristics: Speed, position,... Operations: Move, stop, accelerate,... 4

Objects in C Static Locals C allows functions to possess some state information, hence we can create (very) degenerate objects in C: Behavior: of one sort only Identity: single object int counter(void) { static int n = 0; return ++n; This is a global variable with a limited access. It simulates the state of the function 5

Objects in C Modules More interesting behavior can be achieved by using files and separate compilation in C. Still, Behavior: several functions Identity: single object /* stack.h: interface file */ void push(int val); int pop(void); This is how C simulates a module /* stack.c: implementation file */ #include "stack.h" static int stack[100], sp; void push(int val) { stack[sp++] = val; int pop(void) { return stack[--sp]; 6

int main(int ac, char** av) { FILE *fin; for (++av; *av!= NULL; av++) { if ((fin = fopen(*av, r )) == NULL) continue; Objects in C ADT FILE* is as close as you can get to an object in C. Behavior: many functions Identity: the file pointer State: the file s contents, flags, status,... while (!feof(fin)) putc(fgetc(fin)); This is an Abstract Data Type 7

Identity the property of an object which distinguishes it from all other objects. Identity name An object may have several different names An object may exist without any particular name bound to it Identity state State may change while identity may not Identity is tightly related to lifetime The time span extending from the time an object is first created and consumes space until that space is reclaimed An object can continue to exist even if all references to it are lost Same location + different lifetime different identity 8

Objects may live Object s Lifetime As long as the program is alive E.g., global objects in C++ While a certain block is running E.g., C++ stack (automatic) objects From creation (instantiation) till destruction E.g., C++ heap objects From creation till (after) no longer needed E.g., objects in Java, C#, Smalltalk Garbage Collected languages 9

In many cases, it becomes necessary for a method of an object to explicitly reference the object identity: Namespace ambiguity resolution ::foo or this->foo? Return reference to self Pass self as argument Notation: Self Reference to Identity this in C++, Java, C# self in Smalltalk Current in Eiffel 10

Identity & Equality Two Kinds of Equality: Is this the same object? Names equal if designate same object. Are they in the same state? Names equal if designate objects of the same state. Address 0x1960 12 Foo Bar 0x196C 12 Memory Contents A matter of value vs. reference semantics 11

Identity & Assignment Two Kinds of Assignment: Identity Assignment Reference is duplicated. Only one identity is involved. After the assignment: Two names refer to the same object State Assignment Copy the state information. After the assignment: Two names refer to distinct objects Address 0x1960 12 Foo Bar 0x196C 12 Memory Contents 12

State of Mine Everything is an object every field is an object o Changing the field = changing the object? How can you change a field of all its fields are also object? A matter of language semantics o Value vs. reference A matter of program semantics o Who owns a referenced object

How deep to copy? Duplicating an Object 0-level (aka: pointer copying) 1-level (aka: shallow copying) 2-level... Deep copy Who determines the depth? Parent (duplicated object) Children (object fields) 14

class PList { public Point head; public PList tail; 1-Level Copy PList onelevelcopy() { PList res = new PList(); res.head = head; res.tail = tail; return res; 15

class PList { public Point head; public PList tail; 2-Level Copy onelevelcopy() {... PList twolevelcopy() { PList res = new PList(); res.head = new Point(head.x, head.y); if (tail!= null) res.tail = tail.onelevelcopy(); return res; 16

class PList { public Point head; public PList tail; Deep Copy PList deepcopy() { PList res = new PList(); PList to = res; for (PList from = this; from!= null; from = from.tail) { to.head = new Point(from.head.x, from.head.y); to = to.tail = (from.tail == null)? return res; null : new PList(); 17

Depth Determined By Children public class Point { public final int x, y; public Point(int a, int b) { x = a; y = b; public Point copy() { return this; public class PList { public Point head; public PList tail; public PList copy() { PList res = new PList(); res.head = head.copy(); if (tail!= null) res.tail = tail.copy(); return res; 18

Static Aspect of Objects Attributes: placeholders in which the state is stored Nicknames: Fields, Properties, Instance Variables, Data Members Kinds of attributes: Immutable or Mutable Structure: the set of all attributes State: the current value of all of the object attributes Attributes Structure firstname = John lastname = D oh! age = 42 State 19

Immutable Objects: structure comprises only immutable attributes Example: Integer in Smalltalk, String in Java Extremely useful in parallel programming Kinds of values Static Aspect of Objects Scalars: Integer, Real, Boolean,... Aggregates: Array, List, Tree,... Objects: Invoice, Reservation,... Kinds of state representations Value semantics Reference/pointer semantics 20

Dynamic Aspect of Objects Active Object: encompasses its own thread of control; may undergo spontaneous state changes. Example: Ada s tasks, Java Runnable Quite rare in sequential OOPLs. Passive Object: can change state only if operated by other objects. Operations: An object may be queried for its state or requested to change it using its methods. Requestor should not have direct access to attributes. State encapsulation is enforced in many OOPLs. 21

Dynamic Aspect of Objects Message Passing: the means of communication between a client and object. Client: send a message. a symbolic name (called selector in Smalltalk) optional arguments. Object: invoke a method, optionally return an answer. Methods + Messages are called member functions in C++. 22

Examples of Messages The object vehicle can receive messages such as: Move forward at a given speed Accelerate Decelerate Stop The object list can receive messages such as: Add an element X Remove an element Y Return the length of yourself Sort yourself according to a given criteria Concatenate yourself with another list object Print yourself 23

Different Objects, Same Message, Different Methods In Object Oriented Programming, the message rotate left n degrees could be implemented differently by different objects A messages is the abstraction of a function call Shape: Do nothing if n == 0. Otherwise Rotate left n degrees. Circle: Do nothing. Rectangle: Do nothing if n == 180, 360,... Otherwise shape rotate. Square: Do nothing if n == 90, 270,... Otherwise rectangle rotate. 24

Protocol and Behavior Behavior: the way an object acts and reacts internal state changes message sent to other objects returned value Protocol: the envelope of the behavior 25

Kinds of Operations Mutator (Setter): alters state Inspector (selector, Getter): a query on the object s state. Constructor: creates a new object and/or initializes its state. Destructor: frees object s space and/or does other clean-up operations. Revealer: exposes an internal part of an object for direct external manipulation. 26

Operations on a Date class Date { public: // Constructor Date(int day = -1, int month = -1, int year = -1); // Inspectors int day(void) const { return d; int month(void) const { return m; int year(void) const { return y; // Mutators int day(int day); int month(int month); int year(int year); // Destructor ~Date(void) { cout << "Sic transit gloria mundi"; private: int d; int m; int y; ; In C++, as in many* other OOPLs, most* objects are instances of a class oop 27

Mutators of the Date Class int Date::day(int day) { Note that the mutators are not pure; they int res = d; d = day; also serve an inspection purpose return res; int Date::month(int month) { int res = m; Such mixed mode programming is m = month; counter purity, but may be useful return res; int Date::year(int year) { int res = y; y = year; return res; 28

Constructor of the Date Class Date::Date(int day, int month, int year) : d(day), // Constructor header: m(month), // Initialize all data members y(year) { // Additional initialization steps // Error checking // Accounting for leap year //... 29

Operations in an Array Class class Array { public: // Constructor Array(int n_): n(n_), buff(new double[n]) { // Destructor ~Array(void) { delete[] data; // Inspectors int n(void) { return n; double at(int i) { return buff[i]; // Revealer double& elem(int i) { return buff[i]; private: int n; float *buff; ; Revealers can serve the purpose of both inspectors and mutators. 30