Object Oriented Programming

Similar documents
Object Oriented Programming

CS1150 Principles of Computer Science Objects and Classes

Principles of Object Oriented Programming. Lecture 4

Programming II (CS300)

Chapter 15: Object Oriented Programming

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

CHAPTER 7 OBJECTS AND CLASSES

Recitation 3 Class and Objects

Lecture 5: Methods CS2301

Chapter 4 Defining Classes I

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

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

Inheritance and Polymorphism

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

Classes. Classes as Code Libraries. Classes as Data Structures

Chapter 4: Writing Classes

CHAPTER 7 OBJECTS AND CLASSES

MIDTERM REVIEW. midterminformation.htm

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

CIS 110: Introduction to Computer Programming

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth

Programming II (CS300)

ECOM 2324 COMPUTER PROGRAMMING II

PART 1. Eclipse IDE Tutorial. 1. What is Eclipse? Eclipse Java IDE

Chapter 4. Defining Classes I

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide


Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Chapter 4. Defining Classes I

Object-Oriented Programming

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Java Bytecode (binary file)

Lecture 2: Java & Javadoc

Chapter 6 Introduction to Defining Classes

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Java and OOP. Part 2 Classes and objects

EECS168 Exam 3 Review

What will this print?

Anatomy of a Class Encapsulation Anatomy of a Method

Chapter 5: Classes and Objects in Depth. Information Hiding

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

Handout 7. Defining Classes part 1. Instance variables and instance methods.

COMP 401 Spring 2014 Midterm 1

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Java Classes and Objects

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Programming I. Course 9 Introduction to programming

Ch 7 Designing Java Classes & Class structure. Methods: constructors, getters, setters, other e.g. getfirstname(), setfirstname(), equals()

CS112 Lecture: Defining Instantiable Classes

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

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

Assignment 1 due Monday at 11:59pm

Object Oriented Programming in C#

Java Object Oriented Design. CSC207 Fall 2014

Abstraction in Software Development

STUDENT LESSON A5 Designing and Using Classes

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

Methods and Data (Savitch, Chapter 5)

PREPARING FOR THE FINAL EXAM

Chapter 11: Create Your Own Objects

Inheritance (Part 5) Odds and ends

Computer Science II (20073) Week 1: Review and Inheritance

COMPSCI 105 S Principles of Computer Science. Classes 3

Example: Fibonacci Numbers

Encapsulation in Java

Chapter 2: Java OOP I

CSC148 Intro. to Computer Science

ENCAPSULATION AND POLYMORPHISM

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Object-Oriented Programming Concepts

CS304 Object Oriented Programming Final Term

Java Classes, Inheritance, and Interfaces

HST 952. Computing for Biomedical Scientists Lecture 5

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

Introduction to Classes and Objects. David Greenstein Monta Vista High School

(infinitespeak.wordpress.com) Classes and Structs. Dr. Sarah Abraham

CS/ENGRD 2110 FALL Lecture 5: Local vars; Inside-out rule; constructors

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

SOAPScript For squeaky-clean code, use SOAPScript Language Summary Bob Nisco Version 0.5 β

JAVA: A Primer. By: Amrita Rajagopal

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

CS 351 Design of Large Programs Coding Standards

(a) Write the signature (visibility, name, parameters, types) of the method(s) required

How to define your own classes that implement abstractions. How to pass information to methods and how methods return values.

Ch 7 Designing Java Classes & Class structure

Object Oriented Programming (II)

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Understanding Inheritance and Interfaces

class objects instances Fields Constructors Methods static

OBJECT ORIENTED PROGRAMMING

This Week. Fields and Variables. W05 Example 1: Variables & Fields. More on Java classes. Constructors. Modifiers

Week 3 Classes and Objects

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Recursion 1. Recursion is the process of defining something in terms of itself.

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

Transcription:

Object Oriented Programming

Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2

Review: Objects In Java and other Object-Oriented Programming (OOP) languages, the focus is on objects Objects are entities that can do actions or be acted upon in a Java program All objects have Properties These are the data about an object In Java we call them attributes or fields or instance variables Behaviours (actions) In Java they are implemented as methods (more specifically, instance methods) 1-3

Review: Objects and Classes Every object belongs to a specific class Objects that belong to the same class have the same properties and can perform the same actions We can think of a class as being a template or pattern or model or definition for objects of that class 1-4

Review: Object-Oriented Programming Object-oriented programs consist of interacting objects Objects are defined by classes Objects are created by objects of other classes (client classes) which use them in implementing a programming solution to a problem 1-5

Example: Social Networking Suppose we want to keep track of social contact information for our friends / relatives We wish to write a program that allows us to add contact information of a friend to our list of friends, remove a contact from the list, and print information about all our contacts. 1-6

Software Development Life Cycle The process of designing a computer program has several steps: Specification Design Implementation Testing and debugging Maintenance 1-7

Example: Social Networking Part of OOP design is deciding on what classes we will need for our problem Let's start with a class called Person, that will model the information about one person in our social network 1-8

Review: Class Definition A class definition consists of Attribute declarations (also known as fields or instance variables) Constructor definitions Method definitions A class definition is stored in a file With the same name as the class With a.java extension on the file 1-9

Example: Person Class Attributes (instance variables, fields) What kind of information do we want to have about a person? Let s keep it short for now Person's name Email address What type should each of these be? A name can be a string An email address can be a string 1-10

Example Python: Person Class class Person: def init (self, firstname=, lastname,= email= ): self.firstname = firstname self.lastname = lastname self.email = email Note in Python we can assign default values to the attributes in this case we used an empty string 1-11

Example Java: Person Class public class Person{ /* Attribute declarations */ private String lastname; private String firstname; private String email; Why are the attributes private? Note that the instance variables are just being declared here (not explicitly assigned values) 1-12

Review: Constructors A constructor is a special method that is called automatically when an object is created with the new operator Its purpose is to initialize the attributes of an object when the object is created In Python we use the special method init to do the job of a constructor In Java a constructor has the same name as the class name 1-13

Example: Person class /** * Constructor initializes the person's name * and email address */ public Person(String firstname, String lastname,string email) { this.lastname = lastname; this.firstname = firstname; this.email = email; } Compared to Python, in Java one must EXPLICITLY give types to the attributes. Also note the difference between the keyword this vs Python s self. 1-14

Review: Terminology Keyword this similar to self in Python Scope of variables Scope refers to the parts of the code in which those variables can be used Scope of instance variables? Formal parameters What is their scope? 1-15

Example: Person Class What methods might we want to have? accessor methods (aka getters) modifier methods (aka setters) tostring method (in Python this is repr or str equals method ( in Python this is eq ) two Person objects are the same if they have the same first name and same last name 1-16

Java /** * setemail method sets the person's email address * @param email */ public void setemail (String email) { } this.email = email; Example: Person class Python """ setemail method sets the person's email address. :param email: email address to set """ def setemail(self,email): self.email=email Note that Python uses WHITESPACE to tie blocks of code together Java uses BRACES and SEMICOLONS (you should still code with whitespace as well) What is this @param? Javadoc documentation (we will do it in Lab 2) 1-17

Python Example: Person class def repr (self): s = self.firstname +" " self.lastname + \t + self.email return s Java /** * tostring method returns a string representation of the person * @return string with first name and last name, email address */ public String tostring() { } String s = this.firstname + " " + this.lastname + "\t" + this.email ; return s; 1-18

Discussion What is the return type of this method? What is \t? What kind of variable is s? A reference variable of type String What is its scope? It is a local variable 1-19

Python def equals(self, other): if self.firstname == other.getfirstname() and self.lastname == other.getlastname() : return True else : Java /** * equals determines whether two persons have the same name * @param other other Person object that this is compared to * @return true if they have the same first and last name, false otherwise */ public boolean equals(person other) { if (this.firstname.equals(other.firstname) && this.lastname.equals(other.lastname)) else } return False return true; return false; What is this.firstname? other.firstname? Where is the equals method that is used in the code? 1-20

Example: SocialNetwork Class We're now ready to provide a class that allows us to keep track of our social contacts What attributes might it have? A list of Person objects We'll use an array as our data structure (this is similar to the notation of a list in Python) A count of the number of friends currently in the list Why is this not necessarily the same as the size of the array? 1-21

Example: SocialNetwork Class Python: from Person import Person class SocialNetwork: def init (self,num=0): self.friends =[] self.numfriends =num Java: /* Attribute declarations */ // array of persons (list of friends) private Person[] friendlist; //current number of friends in list private int numfriends; /* Constant definition */ private final int DEFAULT_MAX_FRIENDS = 10; Notice In Python we declare the attributes IN the constructor itself 1-22

Review: Terminology Keyword final (no such thing in Python, by convention we used all capitalized words to represent a constant) Array declaration [] (array s and python lists do NOT always act the same) 1-23

Example: SocialNetwork Class Constructors: One that creates an array of default size One that takes the size of the array as a parameter What do we call it when there is more than one constructor? overloading In Python we do this by setting defaults in the method 1-24

Python: from Person import Person class SocialNetwork: def init (self,num=0): self.friends =[] self.numfriends =num Notice how there is only one constructor for Python but it uses default values to allow for different uses of it. Also note than in Java arrays must MUST have an specified size; lists can grow dynamically in Python. Java: /** * Constructor creates Person array of default size */ public SocialNetwork () { friendlist = new Person[DEFAULT_MAX_FRIENDS]; numfriends = 0; } /** * Constructor creates Person array of specified size * @param max maximum size of array */ public SocialNetwork(int max) { friendlist = new Person[max]; numfriends = 0; }

Discussion What is stored in the friendlist array after the following is executed? friendlist = new Person[DEFAULT_MAX_FRIENDS]; How does this differ from Python? self.friends =[] 1-26

Example: SocialNetwork Object contacts = new SocialNetwork(5); contacts numfriends 0 friendlist 1-27

Example: SocialNetwork Class Instance methods: let's start with methods to add a person to the list remove a specified person from the list clear the list, i.e. remove all persons return how many persons are in the list tostring (we will add other methods later) 1-28

Python: def add(self, first, last, email): afriend = Person(first,last,email) self.friends.append(afriend) self.numfriends = len(self.friends) Add method Java: /** * add method adds a person to the list * @param firstname * @param lastname * @param email */ public void add (String firstname, String lastname, String email) { // create a new Person object Person friend = new Person (firstname, lastname, email); // add it to the array of friends // but, what if array is not big enough? // double its capacity automatically if (numfriends == friendlist.length) expandcapacity(); // add reference to friend at first free spot in array } friendlist [numfriends] = friend; numfriends++;

Example: SocialNetwork Object contacts = new SocialNetwork(5); After 3 friends are added it will look like this: contacts numfriends 3 friendlist P1 P2 P3 3 Person objects Note that numfriends also acts as the index of the first free spot in the array! 1-30

Review: Arrays An array has a particular number of cells when it is created (its capacity) What happens when an array is full and we try to store past the last element in the array? An exception is thrown What happens then? We can instead automatically expand the capacity of the array in our code! 1-31

/** * expandcapacity method is a helper method * that creates a new array to store friends, with twice * the capacity of the existing one */ private void expandcapacity() { Person[] largerlist = new Person[friendList.length * 2]; for (int i = 0; i < friendlist.length; i++) largerlist [i] = friendlist [i]; } friendlist = largerlist; Note in Python we did not have to do this as lists can grow dynamically 1-32

Review: Terminology Helper method Array length Scope of variables: what is the scope of each of the following variables? friendlist largerlist i 1-33

Python def repr (self): s = "" for element in self.friends: s = s + "\n" + element.getfriend() return s tostring Java /** * tostring method returns a string representation of all persons in the list * @return string representation of list */ public String tostring() { String s = ""; for (int i = 0; i < this.numfriends; i++){ s = s + friendlist[i].tostring() + "\n" ; } return s; } What is ""? "\n"? 1-34

Python: def remove(self, first, last): i = -1 for element in self.friends: if element.getfirstname() == first and element.getlastname() == last: i = self.friends.index(element) if i > -1: self.friends.pop(i) self.numfriends = len(self.friends) return True else: return False remove method Java: /** * remove method removes a specified friend from the list * @param firstname first name of person to be removed * @param lastname last name of person to be removed * @return true if friend was removed successfully, false otherwise */ public boolean remove (String firstname, String lastname) { final int NOT_FOUND = -1; int search = NOT_FOUND; Person target = new Person(firstName, lastname, ""); // if not found, can't remove if (search == NOT_FOUND) return false; // target person found, remove by replacing with // last one in list friendlist[search] = friendlist[numfriends - 1]; friendlist[numfriends - 1] = null; numfriends -- ; // if list is empty, can't remove if (numfriends == 0) return false; // search the list for the specified friend for (int i = 0; i < numfriends && search == NOT_FOUND; i ++) if (friendlist [i].equals(target)) search = i; } return true; 1-35

Example: SocialNetwork Object Suppose the target person to be removed was the first one (P1) ; after it is removed, we will have: contacts numfriends 2 friendlist P3 P2 2 Person objects 1-36

Discussion The search in the remove method is called a linear search It starts at the beginning and continues in a sequential manner Why have we used a constant definition here, and why is it -1? final int NOT_FOUND = -1; Where is the equals method of the line if (friendlist [i].equals(target)) defined? 1-37

Discussion Why is it OK to replace the reference to the found Person with the last one in the list? 1-38

Exercises Write getnumfriends Write clearfriends 1-39

Example: Using the SocialNetwork Class Python: def main(): from SocialNetwork import SocialNetwork from Person import Person contacts = SocialNetwork(); contacts.add("snoopy","dog","snoopy@uwo.ca"); contacts.add("felix","cat","felix@uwo.ca"); contacts.add("mickey","mouse","mickey@uwo.ca"); print(contacts) print( I have, contacts.getnumfriends(), friends in my contact list ) main() Java: public class MyFriends { public static void main (String args[]) { SocialNetwork contacts = new SocialNetwork(); contacts.add("snoopy", "Dog", "snoopy@uwo.ca"); contacts.add("felix", "Cat", "felix@uwo.ca"); contacts.add("mickey", "Mouse", mickey@uwo.ca); } System.out.println(contacts.toString()); System.out.println("I have " + contacts.getnumfriends() + " friends in my contact list."); } 1-40

Discussion Note that if we had System.out.println(contacts); then Java would automatically invoke the tostring method of the class that contacts belongs to How many friends could you add to your list of friends, in an application program that uses our SocialNetwork class? 1-41

Exercise: Expand the SocialNetwork Class The SocialNetwork class could use some more methods in order to be useful! A method that writes the list to a file A method that reads the list from a file A method that searches for a particular friend in the list, and returns the email address Others? 1-42

Review: Passing Parameters Why are methods written with parameter lists? So that the methods can be more general We can use methods with different values passed in as parameters 1-43

Review: Passing Parameters How are parameters actually passed? The variable in the parameter list in the method definition is known as a formal parameter When we invoke a method with a parameter, that is known as an actual parameter 1-44

Passing Parameters: How it Works public class MyFriends { { public static void main(string[] args) { contacts.add("felix", "Cat", "felix@uwo.ca");. public class SocialNetwork { public void add (String firstname, String lastname, String email) { actual parameters are provided by the calling program when it invokes the method formal parameters are part of the method definition When the add method is executed, the value of each actual parameter is passed by value to the corresponding formal parameter variable 1-45

Aspects of Object-Oriented Design Modularity Information Hiding Encapsulation 1-46

Aspects of Program Design: Modularity Modularity refers to subdividing a large problem into smaller components, or modules, to make the design of a solution easier Modules should be as independent from each other as possible Each module should perform one welldefined task 1-47

Aspects of Program Design: Information Hiding Information hiding refers to making implementation details inaccessible To users of a program (they do not need to know about implementation details) To other modules in a program (they cannot see nor change the hidden details) Example: attributes (instance variables) in a class definition are private What parts of a program can access instance variables directly? 1-48

Aspects of OOP Design: Encapsulation Object-oriented Design produces modular solutions We identify the components involved within the problem: the objects An object has data: characteristics (attributes) And behaviours (operations) Combining the data and the operations on the data is called encapsulation They are combined in the class definition 1-49