Programming Abstractions

Slides:



Advertisements
Similar presentations
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Advertisements

Chapter 14: Overloading and Templates
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Constructors and Encapsulation reading: self-checks: #10-17.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, this reading: self-checks: #13-17 exercises:
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
1 Warm-Up Problem Just like with primitive data types (int, double, etc.), we can create arrays of objects. ex: bankAccount employees[100]; Problem: It’s.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
CS 106X Classes and Objects
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
1 C++ Classes & Object Oriented Programming Overview & Terminology.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Constructors; Encapsulation reading: self-checks: #13-18,
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Classes Object-oriented programming: Example: Bank transactions
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Introduction to Classes
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
suggested reading: Java Ch. 6
Introduction to Classes
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Object initialization: constructors
Topic 28 classes and objects, part 2
Building Java Programs
Chapter 6 Class Definitions and Member Functions
Chapter 9 Objects and Classes
Topic 29 classes and objects, part 3
Building Java Programs
Building Java Programs
Building Java Programs
Classes.
CISC/CMPE320 - Prof. McLeod
Building Java Programs
Building Java Programs
JAVA CLASSES.
Kinds of methods accessor: A method that lets clients examine object state. Examples: distance, distanceFromOrigin often has a non-void return type mutator: A.
Java Programming Language
Building Java Programs
Building Java Programs
Lecture 8-2: Object Behavior (Methods) and Constructors
Building Java Programs
Lecture 8 Object Oriented Programming (OOP)
Topic 29 classes and objects, part 3
(4 – 2) Introduction to Classes in C++
Building Java Programs
Topic 29 classes and objects, part 3
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Programming Abstractions CS106B Cynthia Lee

Topics du Jour: Make your own classes! Needed for Boggle assignment! We are starting to see a little bit in MarbleBoard assignment as well

Classes in C++ Making your own kinds of objects!

Class examples A calendar program might want to store information about dates, but C++ does not have a Date type. A student registration system needs to store info about students, but C++ has no Student type. A bank app might want to store information about users' accounts, but C++ has no BankAccount type. However, C++ does provide a feature for us to add new data types to the language: classes. Writing a class defines a new data type.

Classes and objects (6.1) class: A program entity that represents a template for a new type of objects. e.g. class Vector defines a new data type named Vector and allows you to declare objects of that type. objects: Entities that combines state and behavior. object-oriented programming (OOP): Programs that perform their behavior as interactions between objects. A new kind of abstraction: Separation between concepts and details. Objects provide abstraction.

Client, class, object Client program Class Object object int main() { ... - interacts with class and objects asks class to construct a new object Class - what goes into each object - how to construct new objects send/receive messages with object by calling member functions (never directly access private data) Object - member functions (public behavior) memberFunction1() memberFunction2() - member variables (private data) ivar1 [___] (encapsulated) ivar2 [___] object constructs

Client, class, object: an example you already know! This was from the 3rd lecture: int main() { Grid<bool> board(8,8); for (int i=0; i<board.numRows(); i++){ for (int j=0; j<board.numCols(); j++){ board[i][j] = false; } return 0;

Elements of a class member variables: State inside each object. Also called "instance variables" or "fields" Declared as private Each object created has a copy of each field. member functions: Behavior that executes inside each object. Also called "methods" Each object created has a copy of each method. The method can interact with the data inside that object. constructor: Initializes new objects as they are created. Sets the initial state of each object as it is being created. Often accepts parameters for the initial state of the fields.

Class Interface vs. code INTERFACE declarations in .h file IMPLEMENTATION definitions (code) in .cpp file Class

Interface vs. code In C++, when writing classes you must understand separation of: interface: Declarations of functions, classes, members, etc. implementation: Definitions of how the above are implemented. C++ implements this separation using two kinds of code files: .h: A "header" file containing only interface (declarations). .cpp: A "source" file containing definitions. When you define a new class Foo, you write Foo.h and Foo.cpp. The content of .h files is "#included" inside .cpp files. Makes them aware of declarations of code implemented elsewhere. At compilation, all definitions are linked together into an executable.

Interface: Structure of a .h file // classname.h #ifndef _classname_h #define _classname_h class declaration; #endif This is protection in case multiple .cpp files include this .h, so that its contents won't get declared twice

Interface: A class declaration class ClassName { // in ClassName.h public: ClassName(parameters); // constructor returnType name(parameters); // member functions returnType name(parameters); // (behavior inside returnType name(parameters); // each object) private: type name; // member variables type name; // (data inside each object) }; IMPORTANT: must put a semicolon at end of class declaration (argh)

Class example (v1) // Initial version of BankAccount.h. // Uses public member variables and no functions. // Not good style, but we will improve it. #ifndef _bankaccount_h #define _bankaccount_h class BankAccount { public: string name; // each BankAccount object double balance; // has a name and balance }; #endif

Using our objects ba1 name = "Cynthia" balance = 1.25 ba2 // v1 with public fields (bad) BankAccount ba1; ba1.name = "Cynthia"; ba1.balance = 1.25; BankAccount ba2; ba2.name = "Mehran"; ba2.balance = 9999.00; Think of an object as a way of grouping multiple variables. Each object contains a name and balance field inside it. We can get/set them individually. Code that uses your objects is called client code. ba2 name = "Mehran" balance = 9999.00

Member func. bodies In ClassName.cpp, we write bodies (definitions) for the member functions that were declared in the .h file: // ClassName.cpp #include "ClassName.h" // member function returnType ClassName::methodName(parameters) { statements; } Member functions/constructors can refer to the object's fields. Exercise: Write a withdraw member function to deduct money from a bank account's balance.

The implicit parameter implicit parameter: The object on which a member function is called. During the call cynthia.withdraw(...), the object named cynthia is the implicit parameter. During the call mehran.withdraw(...), the object named mehran is the implicit parameter. The member function can refer to that object's member variables. We say that it executes in the context of a particular object. The function can refer to the data of the object it was called on. It behaves as if each object has its own copy of the member functions.

Member func diagram // BankAccount.cpp void BankAccount::withdraw(double amount) { if (balance >= amount) { balance -= amount; } // client program BankAccount cynthia; BankAccount mehran; ... cynthia.withdraw(5.00); mehran.withdraw(99.00); void withdraw(double amount) { if (balance >= amount) { balance -= amount; } name "cynthia" balance 1.25 void withdraw(double amount) { if (balance >= amount) { balance -= amount; } name "mehran" balance 9999

Initializing objects It's bad to take 3 lines to create a BankAccount and initialize it: BankAccount ba; ba.name = "Cynthia"; ba.balance = 1.25; // tedious We'd rather specify the fields' initial values at the start: BankAccount ba("Cynthia", 1.25); // better We are able to this with most types of objects in C++ and Java. You can achieve this functionality using a constructor.

Constructors ClassName::ClassName(parameters) { statements to initialize the object; } constructor: Initializes state of new objects as they are created. runs when the client declares a new object no return type is specified; it implicitly "returns" the new object being created If a class has no constructor, C++ gives it a default constructor with no parameters that does nothing.

Constructor diagram // BankAccount.cpp BankAccount::BankAccount(string n, double b) { name = n; balance = b; } // client program BankAccount b1( "Cynthia", 1.25); BankAccount b2( "Mehran", 9999); BankAccount(string n, double b) { name = n; balance = b; } name balance BankAccount(string n, double b) { name = n; balance = b; } name balance

The keyword this As in Java, C++ has a this keyword to refer to the current object. Syntax: this->member Common usage: In constructor, so parameter names can match the names of the object's member variables: BankAccount::BankAccount(string name, double balance) { this->name = name; this->balance = balance; } this uses -> not . because it is a "pointer"; we'll discuss that later

Preconditions precondition: Something your code assumes is true at the start of its execution. Often documented as a comment on the function's header: // Initializes a BankAccount with the given state. // Precondition: balance is non-negative BankAccount::BankAccount(string name, double balance) { this->name = name; this->balance = balance; } Stating a precondition doesn't really "solve" the problem, but it at least documents our decision and warns the client what not to do. What if we want to actually enforce the precondition?

Throwing exceptions throw expression; Generates an exception that will crash the program, unless it has code to handle ("catch") the exception. // Initializes a BankAccount with the given state. // Precondition: balance is non-negative BankAccount::BankAccount(string name, double balance) { if (balance < 0) { throw "Illegal negative balance"; } this->name = name; this->balance = balance; Why would anyone ever want a program to crash?

Private data private: type name; encapsulation: Hiding implementation details of an object from its clients. Encapsulation provides abstraction. separates external view (behavior) from internal view (state) Encapsulation protects the integrity of an object's data. A class's data members should be declared private. No code outside the class can access or change it.

Accessor functions We can provide methods to get and/or set a data field's value: // "read-only" access to the balance ("accessor") double BankAccount::getBalance() { return balance; } // Allows clients to change the field ("mutator") void BankAccount::setName(string newName) { name = newName; Client code will look like this: cout << ba.getName() << ":$" << ba.getBalance() << endl; ba.setName("Cynthia");

Encapsulation benefits Provides abstraction between an object and its clients. Protects an object from unwanted access by clients. Allows you to change the class implementation. Point could be rewritten to use polar coordinates (radius r, angle θ), but with the same methods. Allows you to constrain objects' state (invariants). Example: Don't allow a BankAccount with a negative balance.

Extra topics Operators and const

Operator overloading Making your own kinds of objects work with operators!

Operator overloading (6.2) C++ allows you to overload, or redefine, the behavior of many common operators in the language: unary: + - ++ -- * & ! ~ new delete binary: + - * / % += -= *= /= %= & | && || ^ == != < > <= >= = [] -> () , Overuse of operator overloading can lead to confusing code. Rule of Thumb: Don't abuse this feature. Don't define an overloaded operator unless its meaning and behavior are completely obvious.

Op overload syntax Declare your operator in a .h file, implement it in a .cpp file. returnType operator op(parameters); // .h returnType operator op(parameters) { // .cpp statements; }; where op is some operator like +, ==, <<, etc. the parameters are the operands next to the operator; for example, a + b becomes operator +(Foo a, Foo b) Overloaded operators can also be declared inside a class (not shown here)

Op overload example // BankAccount.h class BankAccount { ... }; bool operator ==(BankAccount& ba1, BankAccount& ba2); bool operator !=(BankAccount& ba1, BankAccount& ba2); // BankAccount.cpp bool operator ==(BankAccount& ba1, BankAccount& ba2) { return ba1.getName() == ba2.getName() && ba1.getBalance() == ba2.getBalance(); } bool operator !=(BankAccount& ba1, BankAccount& ba2) { return !(ba1 == ba2); // calls operator ==

Make objects printable To make it easy to print your object to cout, overload the << operator between an ostream and your type: ostream& operator <<(ostream& out, Type& name) { statements; return out; } The operator returns a reference to the stream so it can be chained. cout << a << b << c is really ((cout << a) << b) << c Technically cout is being returned by each << operation.

<< overload example // BankAccount.h class BankAccount { ... }; ostream& operator <<(ostream& out, BankAccount& ba); // BankAccount.cpp ostream& operator <<(ostream& out, BankAccount& ba) { out << ba.getName() << ": $" << setprecision(2) << ba.getBalance(); return out; }

Classes and const

The keyword const C++ const keyword indicates that a value cannot change. const int x = 4; // x will always be 4 a const reference parameter can't be modified by the function: void foo(const BankAccount& ba) { // won't change ba Any attempts to modify d inside foo's code won't compile. a const member function can't change the object's state: class BankAccount { ... double getBalance() const; // won't change account On a const reference, you can only call const member functions.