CS 112 Intro to Programming Basic OO Concepts

Size: px
Start display at page:

Download "CS 112 Intro to Programming Basic OO Concepts"

Transcription

1 CS 112 Intro to Programming Basic OO Concepts George Mason University

2 Building up to classes: Python Data Types Primitive Data Types: integer, floating point, boolean, None, etc Complex Data Types: Sequence: String, Tuple, List Mapping: Dictionary Class: User-created 2

3 DEFINING CLASSES

4 Making Our Own Types: Classes We can move beyond the existing types of our language. we're not restricted to using just int, float, str, list, tuple, set, dictionary, Each type can be thought of as a set of values: bool NoneType int person address = {True, False} = {None} = {,-2,-1,0,1,2, } =??? =???

5 Making Our Own Types: Classes We create our own new types with a class definition: a 'blueprint' of what is present for a value of this type: what pieces of data (variables inside) what behaviors (methods available)

6 Example Class Let's define a Person as having a name and an age: # define an entire new class of python values class Person: # method describing how to create any one new Person value def init ( self, name_param, age_param ): # store param to 'long-term' instance variables self. name = name_param self. age = age_param create a Person value (an object) by calling its constructor: george = Person("George",66) this actually calls the init definition, by using the class name Person. Note that the self parameter seems to have been supplied some other way!)

7 Classes in Python Class Definition (blueprint) class definition tells Python everything about the new data type Object Instantiation (creation) An object must be instantiated (created) from the class definition via the init method, to fill in instance variables, before it can be used. Object manipulation (use) Once object exists, we can read/update its data (access its instance variables), and use its behaviors (call its methods) 7

8 Class Definition A Python class definition contains: name (identifier) of the class optional: name of parent class. (often, just object) constructor (method named init ) defines, instantiates the instance variables methods (behavior)

9 Example: The Point class A Point is an (x,y) coordinate pair. data: the actual x, y values. methods: shift, vector_magnitude, etc. We define a Point class once, so that we can make lots of Point objects. our Point methods only work on Points (this is good)

10 Point class class Point: #constructor: how to make a Point. def init (self, xparam, yparam): # creates an x, and a y, for the object. self.x = xparam self.y = yparam init method: tells us how to create a Point object. all methods, not just constructor methods, have self as a first parameter. We must use self to access the object's data and methods from within the class's code

11 Constructor Methods constructor method is named init note: double underscores on both sides ( i n i t ) primary duty: assign values to the object's attributes must have at least one first formal parameter (name it self) may have as many more params as needed/desired. Calling a constructor (via the class name) tells Python to: instantiate (create) a new object of the class data type example: Point(1,2) set the object s initial state (run constructor's code) example: self.x becomes 1, self.y becomes 2. return a reference to the new object to the caller 11

12 Defining Attributes self.x is assigned to create the instance variable named x. re-assigns if we see another self.x assignment all instance variables ought to be added in the constructor. every single Point object we make has its own x, and its own y. class Point: #constructor: how to make a Point. def init (self, xparam, yparam): # creates an x, and a y, for the object. self.x = xparam self.y = yparam

13 Instance Variables We can make many objects from a single class definition. Each object is an instance of the class, so each variable that exists inside the object is called an instance variable. Class Person Address Popsicle Episode <Anything> example instance variables name, age, height state,zip, city, county, street, num color, flavor, size, is_frozen show_name, genre, season, ep_num, runtime <you choose what state is important for your program!> 13

14 POLL 9A class definitions

15 Practice Problem For each of the following, define a class, with its constructor, that represents it. A Student has a name, a student ID, and a GPA. A stop-light has a status which is "red", "green", or "amber". Come up with a good example class. When would it be helpful?

16 CREATING OBJECTS

17 Object Components objects contain two different things: attributes characteristics of the object (instance variables) behaviors actions of the object (methods) 17

18 Using These Types: Making Objects A class defines a new type. objects are the actual values of this type An object instantiates the class definition by calling the init method, supplying values for each parameter except for the first one (which is traditionally named self).

19 Example Objects >>> george_mason = Person("George",66) >>> william = Person("Bill Shakespeare",52) >>> >>> george_mason. age 66 >>> william. age 52 >>> george_mason. name 'George' >>> william. age = (william.age) >>> william. age 454

20 Understanding Objects as Values Each object is an instance of its class type. 5 is an instance of an int. So is 6. They behave differently when we use them. xs=[1,2,3] and ys=[4,5] both refer to lists but contain different data. The same methods are available on each list (such as append, extend, sort, etc), but they respond differently If we modify one, the other is not affected. we're only discussing values here (not aliases) two Person objects are both instances of the Person class. They may have different names, ages, etc. have same methods (b/c each is a Person).

21 Point Objects Create an object an instance of the class by calling the constructor. p1 = Point(1,2) #call constructor p2 = Point(3,4) #call constructor print ("point 1: ", p1.x, p1.y) print ("point 2: ", p2.x, p2.y) print(p1) point 1: 1 2 point 2: 3 4 < main.point object at 0x1005c9ad0> Access attributes with the dot-operator: Syntax: objectexpr. attribute Example: p1. x

22 POLL 9B objects

23 Practice Problem In an interactive session, load your classes from before, and: Create two objects each of your Student and Stoplight classes. print some of their instance variables out modify the values of some instance variables print them again print the whole objects out how do they look? good, bad?

24 DEFINING METHODS

25 Defining Methods A method in our class implements functionality that is only appropriate upon an object of the class. They look a lot like function definitions indented inside of a class. Always have self as first parameter. Each object can use this method on its personal data (through self). The method may: access or update instance values return values based on instance values

26 Adding a Method class Point(object): #constructor, etc. def shift (self, xshift=0, yshift=0): self.x += xshift self.y += yshift the method accesses instance variables through self. values modified directly the "side effect" of calling the method is that x and y change values. no return statement present in our particular shift method, but just like functions, we always return something; return statements are normal in methods just as in functions. in this case, None is implicitly returned

27 Better Printing: provide str definition class Point: # init constructor, etc. def str (self): s = "Point("+str(self.x)+","+str(self.y)+")" return s >>>p1 = Point(1,2) >>>print(p1) Point(1,2) We are overloading the str() functionality. str() looks for the str method and calls it. this is an example of polymorphism: str() works on many types, with str definitions added in ad-hoc fashion.

28 Practice Problem add a go_to_origin method that changes a Point back to the origin. where does it go? what is its return type? how many arguments does it have? add a quadrant method, that returns a number from 1 to 4 based on which quadrant the Point is in. Return 0 if the point is on either axis. 1:(+,+). 2:(-,+). 3:(-,-). 4:(+,-). answer the three 's from the previous question.

29 Practice Problem Create an object of the Point class, and place it not at the origin. Call the shift and origin methods so that you can print subsequent calls to the quadrant method, and get a different answer each time. If you create three Point objects, how many integers were stored in memory? if you call origin() on one of the three Points, does this affect the other two Point objects?

30 Practice Problem add a vector_magnitude method that calculates the distance from the origin, returning the float value. add a slope method that accepts another Point argument, and calculates the slope from the self-point to the argument-point, returning that value.

31 Using a method p1 = Point(1,2) p2 = Point(3,4) print(p1) p1.shift(5,5) print(p1) p1.shift(yshift=3) print(p1) print("\np2:",p2) print("p2:",p2. str ()) print("p2:",str(p2)) Point(1,2) Point(6,7) Point(6,10) p2: Point(3,4) p2: Point(3,4) p2: Point(3,4) Both Point objects have their own state. p1 gets modified repeatedly, but p2 stays the same. They are separate values. Note: the self parameter's argument is p1 itself, so it doesn't show up in the ()'s. It shows up in front of the method name. All methods are called this way.

32 Various Ways to Display p2 = Point(3,4) print("p2:",p2. str ()) print("p2:",str(p2)) print("p2:",p2) p2: Point(3,4) p2: Point(3,4) p2: Point(3,4) we can manually call _str on our Point object if we want. str() looks for a definition of str to call print() calls str() all three have the same effect.

33 Practice Problem What is printed? p1 = Point(1,1) p2 = p1 p2.x = 2 print("first: ",p1) p3 = Point(3,3) p1 = Point(5,5) print("1: ",p1) print("2: ",p2) print("3: ",p3) first: Point(2,1) 1: Point(5,5) 2: Point(2,1) 3: Point(3,3) p2 is an alias for p1, and then p1 is reassigned to a different object memory.

34 Functions vs. Methods Functions define a conversion from arguments to returnvalue. sqrt(25) accepts argument, calculates/returns 5.0 Methods act upon objects of some particular type only, yet also accept arguments and calculate return value. Assumed that it might modify the object's state. You could always define a method as a function instead, but it's tidy to put methods where they belong avoid calling it on incorrect types of data. 34

35 POLL 9C methods

36 SCOPE, VISIBILITY

37 Scope and Methods Method parameters only exist during a particular call of the method. Instance variables' values live as long as the object lives (is accessible from any part of your code) Convention: name parameter and attribute the same. x and self.x are different. y and self.y also. class Point (object): def init (self, x, y): self.x = x self.y = y

38 A Need for Privacy Sometimes data is 'sensitive' either shouldn't be known outside an object, or at least shouldn't be directly modifiable by outsiders. a BankAccount object's balance shouldn't just be readily modifiable, it should only be accessed in controlled fashion: through methods.

39 Unsecure Account class Account: def init (self, start_bal=0): self.bal = start_bal def withdraw(self, amount): self.bal -= amount return amount def deposit(self, amount): self.bal += amount

40 Unsecure Attribute Usage a = Account(50) print(a.bal) a.withdraw(-100) print(a.bal)! a.bal = print(a.bal)!!! withdraw method is too trusting.! the bal attribute shouldn't be directly accessible, neither for reading or writing.

41 Approach to Privacy: Private Attributes/Methods attributes whose identifiers begin with a doubleunderscore are private: the dot-operator access doesn't work from outside the object. unfortunately, Python does allow the programmer to access the private attribute, or private method, via the underscore-classname-attribute name. Example: a SafeAccount object's bal can be accessed outside of the object with accountexpr. _SafeAccount bal

42 Better (Private) Attribute Usage class SafeAccount: def init (self, start_bal=0): self. bal = start_bal def withdraw(self, amount): if amount>0 and self. bal>=amount: self. bal -= amount return amount return 0 def deposit(self, amount): self. bal += max(0,amount) def current_balance(self): return self. bal

43 Secure Attribute Usage a = SafeAccount(50) print(a.current_balance()) a.withdraw(-100) print(a.current_balance()) a.deposit(-100) print(a.current_balance()) #errors (unallowed): # a.bal = # a. bal = #allowed, circumvents privacy: print(a._safeaccount bal) Python still creates underscore-classnameattribute as an attribute, so it's not truly private. This is Python's "we're all adults" approach. Makes it harder, but not impossible, to access it.

44 Practice Problems Thoughts: did making bal private make withdraw or deposit safer? preclude *any* abuses of bank accounts? add a pin number to the bank account. should it be private? how might we use it? (not a simple answer)

45 Recipe: Using OO in Python Choose your data representations when starting up a new project. Some of these choices may mean you create new classes. Add attributes and behaviors to the class definitions, so that they are useful for your particular project. Create objects of this class while implementing your project, instead of just using lists, tuples, etc.??? PROFIT

46 BASICS OF OBJECT-ORIENTED PROGRAMMING

47 Object Oriented Programming In this style, the programmer tries to model the system by defining what objects exist, and how they behave A program is then essentially making the right objects, and then watching them interact or create other objects.

48 Object Oriented Programming create classes for relevant structures of a project. define objects' state/behavior as variables and methods. create objects for everything that interacts, let them interact to model the world.

49 Encapsulation Encapsulation means using barriers or boundaries to keep related things together, and unrelated things apart from each other. Attributes and behaviors are enclosed (encapsulated) within the logical boundary of the object entity In structured or procedural systems, data and code are typically maintained as separate entities (e.g., functions here, and specific lists of data over there) In OO systems, each object contains the data (attributes) and the code (behaviors) that operates upon those attributes 49

50 Abstraction Encapsulation implements the concept of abstraction: details associated with object sub-components are enclosed and hidden within the logical boundary of the object user of object only sees the abstract perspective offered by the object Note - In Python, encapsulation is merely a programming convention other languages (e.g., Java) enforce the concept more rigorously. 50

51 Encapsulation Putting related values and related code (methods) together gives us encapsulation. Good organization always helps! Centralizing definitions means we have one place to make modifications.

52 INHERITANCE

53 Inheritance We can create class definitions out of other classes, adding more variables and more methods. Promotes code reuse by allowing more specific sub-classes to be derived from more generic super-classes defines child class and parent class relations. 53

54 Inheritance child inherits attributes/behaviors of parent may add additional attributes/behaviors thus making the child more specific The child-class type is a subtype of the parentclass type. Every object of child class is still a value of the parent class type. a Student is a Person. A Cat is an Animal. (similar idea:) every int can be represented as a float, but not vice versa. 54

55 Inheritance - example generic attributes/behaviors here: VIN, color, year, etc.; accelerate, brake, etc. Vehicle more specialized attributes/behaviors: 4-wheel drive, towing hitch, etc.; engage 4-wheel drive, open_trunk, etc. Car Truck very specialized details: bed canopy; rear seat DVD player; operate_winch; etc. Pickup SUV 55

56 Aggregation Aggregation is the collecting of other (possibly complex) values. An object can have other objects as data, just like a list can have other lists as items inside of it. Person Behaviors Name addr Objects may declare and instantiate other objects as attributes 56 String Behaviors "George" Address Behaviors city zip Aggregate Objects

57 Aggregation - example Do not confuse: inheritance relationships with aggregate relationships Monitor Each aggregate unit can in turn contain other aggregate units Desktop Computer Base Unit Mother Board A Desktop Computer can contain aggregate units as attributes Disk Drive 57

58 Inheritance vs Aggregation "IS-A": Inheritance embodies the "is-a" relationship: A Student "is a" Person; a Truck "is a" Vehicle. "HAS-A": Aggregation embodies the "has-a" relationship: A Student "has a" GPA. A Car "has a" Wheel.

59 Exceptions Revisited Exception classes heavily utilize an inheritance hierarchy. We can create our own exception classes, add our own useful variables, methods, etc. We can extend existing classes to piggyback on the appropriate exception handling code. go visit our Exceptions slides for more info on making Exception classes.

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

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

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

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Haleh Ashki 2015, updated Peter Beerli 2017 Traditionally, a program has been seen as a recipe a set of instructions that you follow from start to finish in order to complete

More information

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

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 Objects 3 1 Static member variables So far: Member variables

More information

1. Write two major differences between Object-oriented programming and procedural programming?

1. Write two major differences between Object-oriented programming and procedural programming? 1. Write two major differences between Object-oriented programming and procedural programming? A procedural program is written as a list of instructions, telling the computer, step-by-step, what to do:

More information

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

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

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay Computer Science and Engineering Indian Institue of Technology Bombay November 27, 2004 What is Object Oriented Programming? Identifying objects and assigning responsibilities to these objects. Objects

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 8 March 28, 2016 Computational Concepts Toolbox Data type: values, literals,

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Objects and classes Abstract Data Types (ADT). Encapsulation OOP: Introduction 1 Pure Object-Oriented Languages Five rules [Source: Alan Kay]: Everything in

More information

Object Model Comparisons

Object Model Comparisons Object Model Comparisons 1 Languages are designed, just like programs Someone decides what the language is for Someone decides what features it's going to have Can't really understand a language until

More information

CS558 Programming Languages Winter 2013 Lecture 8

CS558 Programming Languages Winter 2013 Lecture 8 OBJECT-ORIENTED PROGRAMMING CS558 Programming Languages Winter 2013 Lecture 8 Object-oriented programs are structured in terms of objects: collections of variables ( fields ) and functions ( methods ).

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

Object-Oriented Programming

Object-Oriented Programming 61A Lecture 15 Announcements Object-Oriented Programming Object-Oriented Programming A method for organizing programs Data abstraction Bundling together information and related behavior John's Account

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes chapter 11 Code Listing 11.1 First Class Introduction to Classes What is a class? If you have done anything in computer science before, you likely will have heard the term object oriented programming (OOP)

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

CSc 110, Autumn Lecture 30: Methods. Adapted from slides by Marty Stepp and Stuart Reges

CSc 110, Autumn Lecture 30: Methods. Adapted from slides by Marty Stepp and Stuart Reges CSc 110, Autumn 2016 Lecture 30: Methods Adapted from slides by Marty Stepp and Stuart Reges Why objects? Primitive types don't model complex concepts well Cost is a float. What's a person? Classes are

More information

Announcements. Last modified: Fri Sep 8 00:59: CS61B: Lecture #7 1

Announcements. Last modified: Fri Sep 8 00:59: CS61B: Lecture #7 1 Announcements Sign-ups for weekly group tutoring offered by the course tutors have been released! Form will close on Saturday, 9/9, at 11:59PM. You will receive room and time assignments on Sunday via

More information

CS61B Lecture #7. Announcements:

CS61B Lecture #7. Announcements: Announcements: CS61B Lecture #7 New discussion section: Tuesday 2 3PM in 310 Soda. New lab section: Thursday 2 4PM in 273 Soda. Programming Contest coming up: 5 October (new date). Watch for details. Last

More information

CSC102 INTRO TO PROGRAMMING WITH PYTHON REVIEW MICHAEL GROSSBERG

CSC102 INTRO TO PROGRAMMING WITH PYTHON REVIEW MICHAEL GROSSBERG CSC102 INTRO TO PROGRAMMING WITH PYTHON REVIEW MICHAEL GROSSBERG MATERIAL EVERYTHING LECTURES HOMEWORKS TEXTBOOK (ALL OF IT) MOSTLY PYTHON 2.6 SOME C++ POTENTIALLY: TRANSLATE PYTHON PROGRAM TO C++ FORMAT

More information

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

Object-oriented basics. Object Class vs object Inheritance Overloading Interface Object-oriented basics Object Class vs object Inheritance Overloading Interface 1 The object concept Object Encapsulation abstraction Entity with state and behaviour state -> variables behaviour -> methods

More information

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright Java Basics Object Orientated Programming in Java Benjamin Kenwright Outline Essential Java Concepts Syntax, Grammar, Formatting, Introduce Object-Orientated Concepts Encapsulation, Abstract Data, OO Languages,

More information

CS 617 Object Oriented Systems Lecture 5 Classes, Classless World:Prototypes, Instance Variables, Class Variables, This/Self 3:30-5:00 pm Thu, Jan 17

CS 617 Object Oriented Systems Lecture 5 Classes, Classless World:Prototypes, Instance Variables, Class Variables, This/Self 3:30-5:00 pm Thu, Jan 17 Objects, Interfaces and CS 617 Object Oriented Systems Lecture 5, Classless World:Prototypes, Instance Variables, Class Variables, This/Self 3:30-5:00 pm Thu, Jan 17 Rushikesh K Joshi Department of Computer

More information

Objects and Classes -- Introduction

Objects and Classes -- Introduction Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

PREPARING FOR THE FINAL EXAM

PREPARING FOR THE FINAL EXAM PREPARING FOR THE FINAL EXAM CS 1110: FALL 2017 This handout explains what you have to know for the final exam. Most of the exam will include topics from the previous two prelims. We have uploaded the

More information

PREPARING FOR PRELIM 2

PREPARING FOR PRELIM 2 PREPARING FOR PRELIM 2 CS 1110: FALL 2012 This handout explains what you have to know for the second prelim. There will be a review session with detailed examples to help you study. To prepare for the

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Python Programming Introduction to Object-Oriented Programming Annemarie Friedrich (anne@cis.uni-muenchen.de) Centrum für Informations- und Sprachverarbeitung LMU München Software objects

More information

Classes, Objects, and OOP in Java. June 16, 2017

Classes, Objects, and OOP in Java. June 16, 2017 Classes, Objects, and OOP in Java June 16, 2017 Which is a Class in the below code? Mario itsame = new Mario( Red Hat? ); A. Mario B. itsame C. new D. Red Hat? Whats the difference? int vs. Integer A.

More information

Ch.7: Introduction to classes (part 2)

Ch.7: Introduction to classes (part 2) Ch.7: Introduction to classes (part 2) Joakim Sundnes 1,2 Hans Petter Langtangen 1,2 Simula Research Laboratory 1 University of Oslo, Dept. of Informatics 2 Oct 27, 2017 Plan for Oct 27 Recap of class

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 5 Modified by James O Reilly Class and Method Definitions OOP- Object Oriented Programming Big Ideas: Group data and related functions (methods) into Objects (Encapsulation)

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

Object Oriented Technology

Object Oriented Technology Object Oriented Technology Object-oriented technology is built upon a sound engineering foundation, whose elements we collectively call the object model. The object model encompasses the principles of

More information

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

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

More information

Object Oriented Programming. Feb 2015

Object Oriented Programming. Feb 2015 Object Oriented Programming Feb 2015 Tradi7onally, a program has been seen as a recipe a set of instruc7ons that you follow from start to finish in order to complete a task. That approach is some7mes known

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Chapter 6 Classes and Objects

Chapter 6 Classes and Objects Chapter 6 Classes and Objects Hello! Today we will focus on creating classes and objects. Now that our practice problems will tend to generate multiple files, I strongly suggest you create a folder for

More information

Computational Concepts Toolbox. Object Oriented Programming. Today: class. Review: Objects

Computational Concepts Toolbox. Object Oriented Programming. Today: class. Review: Objects Computational Concepts Toolbox Object Oriented Programming David E Culler CS8 Computational Structures in Data Science http://insteecsberkeleyedu/~cs88 Lecture 8 March 28, 2016 Data type: values, literals,

More information

CPS122 Lecture: Defining a Class

CPS122 Lecture: Defining a Class Objectives: CPS122 Lecture: Defining a Class last revised January 14, 2016 1. To introduce structure of a Java class 2. To introduce the different kinds of Java variables (instance, class, parameter, local)

More information

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5 Defining Classes and Methods Chapter 5 Objectives Describe concepts of class, class object Create class objects Define a Java class, its methods Describe use of parameters in a method Use modifiers public,

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College August 29, 2018 Outline Outline 1 Chapter 2: Data Abstraction Outline Chapter 2: Data Abstraction 1 Chapter 2: Data Abstraction

More information

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University Lecture 7: Type Systems and Symbol Tables CS 540 George Mason University Static Analysis Compilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing

More information

CS112 Lecture: Defining Instantiable Classes

CS112 Lecture: Defining Instantiable Classes CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:

More information

Programming I. Course 9 Introduction to programming

Programming I. Course 9 Introduction to programming Programming I Course 9 Introduction to programming What we talked about? Modules List Comprehension Generators Recursive Functions Files What we talk today? Object Oriented Programming Classes Objects

More information

9 Working with the Java Class Library

9 Working with the Java Class Library 9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and

More information

Lecture 2: Writing Your Own Class Definition

Lecture 2: Writing Your Own Class Definition Lecture 2: Writing Your Own Class Definition CS6507 Python Programming and Data Science Applications Dr Kieran T. Herley 2017-2018 Department of Computer Science University College Cork Summary Writing

More information

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

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Object-Oriented Programming Concepts

Object-Oriented Programming Concepts Object-Oriented Programming Concepts Real world objects include things like your car, TV etc. These objects share two characteristics: they all have state and they all have behavior. Software objects are

More information

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

Programming for Engineers in Python

Programming for Engineers in Python Programming for Engineers in Python Lecture 5: Object Oriented Programming Autumn 2011-12 1 Lecture 4 Highlights Tuples, Dictionaries Sorting Lists Modular programming Data analysis: text categorization

More information

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

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology Computer Science II OO Programming Classes Scott C Johnson Rochester Institute of Technology Outline Object-Oriented (OO) Programming Review Initial Implementation Constructors Other Standard Behaviors

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING (download slides and.py files follow along!) 6.0001 LECTURE 8 6.0001 LECTURE 8 1 OBJECTS Python supports many different kinds of data 1234 3.14159 "Hello" [1, 5, 7, 11, 13]

More information

Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 5 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 2 is in Assignment 3 is out a quick look back inheritance and polymorphism interfaces the Comparable

More information

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 25 Classes All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Run time Last Class We Covered Run time of different algorithms Selection,

More information

Algorithms and Programming

Algorithms and Programming Algorithms and Programming Lecture 6 Classes, UML, NumPy Camelia Chira Course content Introduction in the software development process Procedural programming Modular programming Abstract data types Software

More information

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

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I Object-Oriented Programming (OOP) Basics CSCI 161 Introduction to Programming I Overview Chapter 8 in the textbook Building Java Programs, by Reges & Stepp. Review of OOP History and Terms Discussion of

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Lecture 15: Object-Oriented Programming

Lecture 15: Object-Oriented Programming Lecture 15: Object-Oriented Programming COMP 524 Programming Language Concepts Stephen Olivier March 23, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Object

More information

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci) Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci) Sung Hee Park Department of Mathematics and Computer Science Virginia State University September 18, 2012 The Object-Oriented Paradigm

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects Outline Problem: How do I create multiple objects from a class Java provides a number of built-in classes for us Understanding

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects Outline Problem: How do I create multiple objects from a class Java provides a number of built-in classes for us Understanding

More information

Anatomy of a Class Encapsulation Anatomy of a Method

Anatomy of a Class Encapsulation Anatomy of a Method Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

OBJECT ORIENTED PROGRAMMING 6

OBJECT ORIENTED PROGRAMMING 6 OBJECT ORIENTED PROGRAMMING 6 COMPUTER SCIENCE 61A October 8, 2012 1 Overview Last week you were introduced to the programming paradigm known as Object Oriented Programming. If you ve programmed in a language

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Building custom components IAT351

Building custom components IAT351 Building custom components IAT351 Week 1 Lecture 1 9.05.2012 Lyn Bartram lyn@sfu.ca Today Review assignment issues New submission method Object oriented design How to extend Java and how to scope Final

More information

Review 2. Classes and Subclasses

Review 2. Classes and Subclasses Review 2 Classes and Subclasses Class Definition class (): """Class specification""" class variables (format: Class.variable) initializer ( init ) special method definitions

More information

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

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction Lecture 13: Object orientation Object oriented programming Introduction, types of OO languages Key concepts: Encapsulation, Inheritance, Dynamic binding & polymorphism Other design issues Smalltalk OO

More information

Object Oriented Software Development CIS Today: Object Oriented Analysis

Object Oriented Software Development CIS Today: Object Oriented Analysis Object Oriented Software Development CIS 50-3 Marc Conrad D104 (Park Square Building) Marc.Conrad@luton.ac.uk Today: Object Oriented Analysis The most single important ability in object oriented analysis

More information

Object Oriented Programming with Java

Object Oriented Programming with Java Object Oriented Programming with Java What is Object Oriented Programming? Object Oriented Programming consists of creating outline structures that are easily reused over and over again. There are four

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming ECE 364 Software Engineering Tools Laboratory Lecture 7 Python: Object Oriented Programming 1 Lecture Summary Object Oriented Programming Concepts Object Oriented Programming in Python 2 Object Oriented

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #23: OO Design, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia HW#5 due Tuesday And if you re cheating on (or letting others see your) HW#5

More information

Introduction to Software Testing Chapter 2.4 Graph Coverage for Design Elements Paul Ammann & Jeff Offutt

Introduction to Software Testing Chapter 2.4 Graph Coverage for Design Elements Paul Ammann & Jeff Offutt Introduction to Software Testing Chapter 2.4 Graph Coverage for Design Elements Paul Ammann & Jeff Offutt www.introsoftwaretesting.com OO Software and Designs Emphasis on modularity and reuse puts complexity

More information

OBJECT ORIENTED PROGRAMMING 7

OBJECT ORIENTED PROGRAMMING 7 OBJECT ORIENTED PROGRAMMING 7 COMPUTER SCIENCE 61A July 10, 2012 1 Overview This week you were introduced to the programming paradigm known as Object Oriented Programming. If you ve programmed in a language

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 7a Andrew Tolmach Portland State University 1994-2016 Values and Types We divide the universe of values according to types A type is a set of values and a

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

5.6.1 The Special Variable this

5.6.1 The Special Variable this ALTHOUGH THE BASIC IDEAS of object-oriented programming are reasonably simple and clear, they are subtle, and they take time to get used to And unfortunately, beyond the basic ideas there are a lot of

More information

Consolidation and Review

Consolidation and Review Consolidation and Review Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction to Computer Science, 2 nd edition,

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems Basics of OO Programming with Java/C# Basic Principles of OO Abstraction Encapsulation Modularity Breaking up something into smaller, more manageable pieces Hierarchy Refining through levels of abstraction

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information