Object Orientation A Crash Course Intro. What is an Object? An object, in the context of object- oriented programming, is the association of a state with.

Slides:



Advertisements
Similar presentations
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Advertisements

CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
CS 106 Introduction to Computer Science I 03 / 21 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 23 / 2007 Instructor: Michael Eckmann.
1 Writing a Good Program 5. Objects and Classes in C++
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
C++ Structures: Classes In C++, the concept of structure has been generalized in an object-oriented sense: –classes are types representing groups of similar.
Classes in C++ Bryce Boe 2012/08/15 CS32, Summer 2012 B.
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Object Oriented Programming Philosophy. Part 1 -- Basic Understanding & Encapsulation.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Defining New Types Lecture 21 Hartmut Kaiser
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
10-Nov-15 Java Object Oriented Programming What is it?
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Object Oriented Programming
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
1 Using const in C++ Classes In the presence of pointers we must take steps to ensure the integrity of the object Can use const method definitions The.
The const Keyword Extreme Encapsulation. Humble Beginnings There are often cases in coding where it is helpful to use a const variable in a method or.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
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.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
Exceptions When Good Code Goes Bad. Analysis Object-orientation is all about recognizing the different “actors” at work in the system being modeled. –
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Memory Management.
Classes and Objects: Encapsulation
Phil Tayco Slide version 1.0 Created Sep 18, 2017
Motivation and Overview
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
slides created by Ethan Apter and Marty Stepp
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
(4 – 2) Introduction to Classes in C++
Presentation transcript:

Object Orientation A Crash Course Intro

What is an Object? An object, in the context of object- oriented programming, is the association of a state with a set of behaviors. – State: its fields, or “member variables” – Behaviors: its associated methods, or “member functions.”

A First Object #include using namespace std; // a very basic C++ object class Person { public: string name; int age; } int main() { … }

A First Object using namespace std; // a very basic C++ object class Person { public: string name; int age; } Note – this is not a properly-designed class according to object-orientation principles.

Exercise 1 Write the Person definition as given with public member fields Write a little main function to  declare a Person object and then  ask for user input  set its fields  print the object fields from the object itself (NOT your input!) Compile and test your program

Analysis Let’s take a look at the process and criteria by which we can assess the design of our object. – This is part of software engineering. – Things to consider: What do we consider to be a “well-designed” class? What do we consider to be a “poorly- designed” class?

Exercise 1.5 Get up and walk around a bit Introduce yourself to a classmate or two Talk to your classmates about what makes a well-designed class You have 3 minutes

Analysis Object-orientation is all about recognizing the different “actors” at work in the system being modeled. – First, the different data available within the system are organized appropriately. – Secondly, functionalities relating to the state of data and its management are bound to that data.

Analysis Object-orientation is all about recognizing the different “actors” at work in the system being modeled. – These objects (“actors”) may then interact with other objects through well- formed, bounded relationships.

Analysis For now, let’s examine how we should look at individual objects – the “actors” in a program. – Each object should be composed of a set of related data that represents some logical unit within the program. – In this case, this would be our “Person” class.

Analysis 1. Inputs: what does our object need in order to be properly formed? – Both from outside, and for internal representation? 2. Outputs: what parts of our object are needed by the outside world? – What might some other part of the program request from it?

Analysis 1. Constraints: should our object have limitations imposed on it, beyond those implied by the language we’re using? – Some of our internal state variables (fields) may allow values which make no sense in the context of what our object represents.

Analysis 1. Assumptions: Are we assuming something in our construction of the class which might have to change later? – We wish to minimize these (in the long run at least) as much as possible.

A First Object // a very basic C++ object class Person { public: string name; int age; } What is bad about the design of our current “Person” class?

Encapsulation Encapsulation refers to the idea that an object should protect and manage its own state information. – In a way, each object should behave like its own entity. Data security is enforced by the object definition itself. – This allows a programmer to make ensure that the data being represented is always in a consistent form.

Encapsulation Generally speaking, objects should never make their fields public. – A public field can be accessed and modified at any time from code that has a reference to the object, which can invalidate its internal state.

Encapsulation Note that encapsulation is motivated by the desire to enforce constraints on our object. – How can we make sure our object is always in a proper, well-formed state if we can’t limit how others modify it?

Encapsulation In object-oriented languages, objects may set their fields to be inaccessible outside of the class. – To do this, one may use the access modifier private. This restricts access to the “ private ” field or method to only code in the class in which said field or method is defined.

A First Object // a very basic C++ object class Person { public: string name; int age; } So, instead of marking the fields as public …

A First Object // a very basic C++ object class Person { private: string name; int age; } We want to mark them as private.

Exercise 2 Change the Person definition to have private member fields Do not change the main() function Compile and test your program What happened? Stand up and walk around when you are done – discuss with other milling about

A First Object // a very basic C++ object class Person { private: string name; int age; } This creates a new problem, though. – How can we initialize our object?

Initialization By default, when no constructor exists for a class, C++ creates a “default” constructor with no internal code. – Note: this “default” constructor will initalize nothing within the class. – Java’s default constructor acts differently, setting values to zeros and nulls.

Initialization By default, when no constructor exists for a class, C++ creates a “default” constructor with no internal code. Typically, we will need to create our own constructors to ensure the class is properly initialized.

A First Object // a very basic C++ object class Person { public: // constructor “prototype” Person(string name, int age); private: string name; int age; }

A First Object Person::Person(string name, int age) { this->name = name; this->age = age; } Note that constructors (and functions) are defined separately from their declarations. – The “ Person:: ” prefix denotes that the Person() constructor belongs to the class Person. – Must make forward declaration/prototype for methods

A First Object Person::Person(string name, int age) { this->name = name; this->age = age; } Something interesting here: note the use of “ -> ”. – “ this ” is a pointer, and it refers to the instance of the class upon which the constructor/function has been called. – p->name is same as (*p).name

Initialization Once one constructor has been coded for a class, the default constructor no longer exists unless it is manually coded. A fully constructed and initialized class object can be called an instance of its class.

Exercise 3 Add the constructor definition as given Change the main() function to set the name and age when your Person object is declared Comment out the member accesses Compile and test your program What do we lack?

A First Object // a very basic C++ object class Person { public: Person(string name, int age); private: string name; int age; } We still have another problem. – How can we actually make use of the class’s data?

Encapsulation Since we’ve set the class fields to private, it is necessary to implement some way of accessing its information – one that does not expose the fields. – The solution? Accessor methods.

A First Object string Person::getName() { return this->name; } int Person::getAge() { return this->age; }

A First Object // a very basic C++ object class Person { public: // constructor & all public methods Person(string name, int age); string getName(); int getAge(); private: string name; int age; } Prototype declarations in public region

A First Object string Person::getName() { return this->name; } Suppose we had a “ Person p ”. The line “ p.getName() ” would return the value for “ name ” from the object represented by “ p ”.

Encapsulation First, note that these accessor methods will be set to public – otherwise, they won’t be of use to code outside of the class. Secondly, these methods retrieve the data without allowing it to be changed. – In Java, String ’s implementation does not allow its internal data to be changed. C++ differs on this point.

Exercise 4 Add the accessor methods as given Include the prototypes in the public section of the class definition Read the member fields using the accessor methods and print them out in main() Compile and test your program Now we have it working! - Get up! But what do we still lack?

Encapsulation What if we need to be able to change one or more of the fields of a class instance? – The (first) solution: mutator methods. – These provide an interface through which outside code may safely change the object’s state. – Think about your code for graph, or for set – adding or deleting an element meant changing some other field(s)...

A First Object void Person::setName(string name) { this->name = name; } void Person::setAge(int age) { this->age = age; } Remember prototypes in class

Exercise 5 Add the mutator methods as given Modify main() after it prints the initial values to read user-supplied values and change the member fields using the mutator methods, then print them out using accessors again Compile and test your program Now we have it all working! High five the person next to you!

Encapsulation Is this necessarily the correct solution, though? – It depends on the purpose for our class. Note that we allow both the “name” of our “Person” and his/her “age” to change, freely.

Encapsulation Should we allow a “Person” to change his/her name? – It does happen in the real world, but for simplicity, let us suppose that we do not wish to allow people to change names. – In such a case, we should remove the setName() method.

Encapsulation void Person::setName(string name) { this->name = name; } void Person::setAge(int age) { this->age = age; }

Encapsulation However, we shouldn’t stop here. If we wish to make sure that a person may never have their name changed, can we make sure that even code from within the class may not change it? – Yes: use the const keyword. In Java: “ final ”.

Encapsulation class Person { private: const string name; int age; } When a field is marked as const, it can only be initialized in a special part of the constructor.

Encapsulation Person::Person(string name, int age) :name(name) { //this->name = name; /* This line would be a compiler error! */ this->age = age; }

Encapsulation Person::Person(string name, int age) :name(name) { //this->name = name; /* This line would be a compiler error! */ this->age = age; } This is the only valid way to initialize a const variable.

Exercise 6 Modify class definition to make name a constant Modify constructor as shown to have name set in special way Compile and test your program What happened? Talk to your neighbor(s) Comment out the mutator for name!

Encapsulation Should we allow a “Person” to change his/her age? – Last time I checked, everyone ages. – However, note that a person’s age cannot change freely. Nobody ages in reverse (Benjamin Button notwithstanding). A person can only add one year to their age, well, every year.

Encapsulation void Person::setName(String name) { this->name = name; } void Person::setAge(int age) { this->age = age; }

Encapsulation void Person::haveABirthday() { this->age++; }

Exercise 7 Change the age mutator to haveABirthday Change main() to cause your person to have a birthday – print age before and after Compile and test your program Do the chicken dance when your program works 6UV3kRV46Zs 6UV3kRV46Zs

Encapsulation At first, encapsulation may seem to be unnecessary. – It does add extra effort to using values that you could just directly access instead. – However, someone else might not know how to properly treat your object and may mess it up if you don’t encapsulate.

Encapsulation There are other benefits to encapsulation. – What if you later realize there’s an even better way to implement your class? – You can provide the same methods for accessing object data while changing its internals as needed.

Encapsulation Is our current implementation of age “the best”? – A possible alternative: track birthdays instead! Birthdays only come once a year, after all, and at known, preset times.

Encapsulation Disclaimer – C++ does not provide a simple way to calculate differences in dates. – As a result, know that the code coming up is representative of what could be done, if the appropriate class existed.

A First Object class Person { private: const string name; const MyDate birthday; //... }

A First Object public class Person { //... public: Person(string name, MyDate bday) int getAge(); string getName(); }

A First Object int Person::getAge() { return MyDate.differenceInYears( MyDate.now(), birthday); } Person::Person(string name, MyDate bday) :name(name), birthday(bday) { }

Analysis Note that the “inputs” to an object are managed through its constructors and mutator methods. The “outputs” are managed through its accessor methods in such a way that the “constraints” are still enforced.

Instantiation When you instantiate an object using Person p("Joe", 21); it allocates space in the current scope and gives you a reference to it When you instantiate an object using Person *p = new Person("Mac", 30); it allocates space in the heap and gives you a pointer to it

Using new When you instantiate an object using Person *p = new Person("Mac", 30); it allocates space in the heap and gives you a pointer to it It can be returned and used outside the scope in which new was used It must be dereferenced to access The object must be explicitly deleted

Using new You must dereference the pointer: Person *p = new Person("Mac", 30); (*p).age = 19;// assuming public cout name; delete p; or Person p = new Person(“Joe”,19);

Exercise 8 Change your original program (with public member variables) to instantiate a person using new Access the member variables using the pointer, both (*p) and p-> Use delete to free the instance when done Compile and test your program

Default Constructor When you make an explicit constructor (like Person(string name, int age)), the default constructor goes away To get it back, you must make it explicitly: Person::Person() {} Note that this will NOT work if you have const member variables!

Exercise 9 Add the default constructor to your program with setName() (NOT the one with const declaration!!!) Use the default constructor and set the name and age in main() Use delete to free the instance when done Compile and test your program