Lecture 2. Object Orientation

Size: px
Start display at page:

Download "Lecture 2. Object Orientation"

Transcription

1 Lecture 2 Object Orientation 1

2 Homework 0 Grades Homework 0 grades were returned earlier this week Any questions? 2

3 Homework 1 Homework 1 is due tonight at 11:59pm You will be graded on: Correctness: 15 points (passing all RSpec tests) Style: 5 points (having no Rubocop style offenses) Best Practices: 5 points (manually graded by TA) For this assignment, you will receive feedback but not actually lose any points Feedback by next Tuesday 3

4 Office Hours Weekday Time Location TA Monday 4-5pm Harrison Mezz Sanjana Sarkar 6-7pm Moore 100 Desmond Howard Tuesday 6-7pm Moore 100 Desmond Howard Wednesday 11am-12pm Moore 100 Sanjana Sarkar 4:30-5:30pm Moore 100 Jackie Askins Thursday 6-7pm Moore 100 Jackie Askins **These are pretty much final, but the locations may changes 4

5 Classes & Objects Classes define clusters of behavior or functionality *Almost* everything in Ruby is an object Every object is an instance of exactly one class You can call methods on almost anything! Because of this, there are no functions in Ruby There is always an object from which to call methods Even arithmetic operations are methods, Ruby adds syntactic sugar to an expression like 1.+(2) to allow us to call it like

6 Creating a Class Use the class and keywords and place class s code between them It is convention to use PascalCase when naming classes Instantiate a class with the new keyword class Person person = Person.new p person.class #=> Person 6

7 Instance Methods Methods that are inted to be called on a specific instance of the class Methods defined in a class are instance methods by default class Person def say_hello p 'Hello' person = Person.new person.say_hello #=> Hello 7

8 Instance Variables Instance variables allow you to remember state in individual objects Names always start with a They are only visible to the instance to which they belong Every instance has its own set of instance variables If you define an instance variable in one instance method in a class, you can access it in any other instance method in that class 8

9 Instance Variables Note that it is bad style in Ruby to prefix methods with set or get, we will fix this soon class Person def = name def person = Person.new person.set_name('jackie') p person.get_name #=> "Jackie" 9

10 Constructors If a method is named initialize, it will be executed when a class is being initialized class Person def initialize p 'Hi, I am being initialized!' Person.new #=> "Hi, I am being initialized!" 10

11 Constructors with Arguments Arguments passed into the new method are also passed into the constructor class Person def = name p "You've initialized a person with name: #{name}" Person.new('Jackie') #=> "You've initialized a person with name: Jackie" 11

12 Reader Methods What we call getters in other languages are referred to as reader methods in Ruby Used to return the value of a variable in a class Share name with variable being returned 12

13 Reader Methods class Person def = name def person = Person.new('Jackie') person.name #=> "Jackie" 13

14 Writer Methods What we call setters in other languages are referred to as writer methods in Ruby Used to set the value of a variable in a class Share name with variable being set followed by an equal sign Ruby uses syntactic sugar to allow us to call the method like it s an assignment 14

15 Writer Methods class Person def = name def def = name person = Person.new('Jackie') person.name = 'Sanjana' p person.name #=> "Sanjana" 15

16 Writer Methods Note that writer methods can do more than just assignment class Person def def name=(name) name *= = name.length > 10? 'Too long' : name person = Person.new person.name = 'Jackie' p person.name #=> "Too long" 16

17 Attr Readers It turns out that the use of reader methods is pretty common We can use the attr_reader method to generate a reader method class Person attr_reader :name def = name person = Person.new('Jackie') p person.name #=> "Jackie" 17

18 Attr Writers We can do the same with writers Using attr_writer will generate a writer method class Person attr_reader :name attr_writer :name person = Person.new person.name = 'Jackie' p person.name #=> "Jackie" 18

19 Attr Accessors It turns out that we can generate both a reader and writer method all in one line by using an attr_accessor class Person attr_accessor :name person = Person.new person.name = 'Jackie' p person.name #=> "Jackie" 19

20 Generating Multiple Methods Multiple symbols can be passed to all three of the attr methods This will generate a reader/writer (or both) for all of the symbols that you provided 20

21 Generating Multiple Methods class Person attr_reader :name, :age, :favorite_color def initialize(name, age, = = = favorite_color person = Person.new('Jackie', 21, 'blue') p person.name #=> "Jackie" p person.age #=> 21 p person.favorite_color #=> "blue" 21

22 Class Methods A method inted to be called on the class itself (as opposed to an instance) is called a class method Defined like an instance method, but starts with self. self indicates the class It cannot call any instance methods Similar to a static method in Java 22

23 Class Methods class Person def self.average_life_expectancy '71.5 years' p Person.average_life_expectancy #=> "71.5 years" 23

24 self This is similar to the this keyword in Java There s always exactly one current object or self The current object is determined by the scope 24

25 self At the top level: self refers to the default object, main Inside of a class definition: self refers to the class object itself Inside of a class method: self refers to the class object Inside of an instance method: self refers to the instance that the method is being called on 25

26 Implicit Receiver All methods must have a receiver When calling student.name, student is the receiver for name What does that mean for instance methods called in another instance method? It has an implicit receiver, and in a class, it is self This is important because: An instance method can be called with an implicit receiver It means there are no functions, only methods, in Ruby 26

27 Method Notation A quick note on method notation ClassName#instance_method Refers to the instance method instance_method in the class ClassName ClassName::class_method Refers to the class method class_method in the class ClassName 27

28 Private Methods By default, all methods are public But you don't want to be able to access every method defined in a class Methods can be made private with the private keyword In the body of a class, all methods physically under the private method are private 28

29 Private Methods class Person def say_hello "Hi, I'm #{name}" private def name 'Jackie' person = Person.new p person.say_hello #=> "Hi, I'm Jackie" p person.name #=> NoMethodError: private method `name' called for #<Person: 0x007fc525011ef8> 29

30 Class Variables Denoted with at the beginning Similar to static variables in Java They are preserved across all instances of the class All instances can access and modify them 30

31 Class Variables class Person = 0 def += 1 def p Person.count #=> 0 Person.new p Person.count #=> 1 They seem harmless, but they re actually pretty bad practice 31

32 Inheritance Classes can inherit from only one other class Classes can be thought of as hierarchical Inheritance is done with the < operator A class will gain all of its parent class s methods, both public and private class Person class Programmer < Person p Programmer.superclass #=> Person 32

33 A Problem with Class Variables It turns out that class variables are more accurately described as class hierarchy variables Not only does the class have access to the variables, its descants will too This is obviously bad As a general rule, don t use class variables unless you mean for this to happen 33

34 A Problem with Class Variables class Bird = 'EVERYWHERE' def self.location p Bird.location #=> "EVERYWHERE" class Penguin < Bird = 'Antarctica' def self.location p Penguin.location #=> "Antarctica" p Bird.location #=> "Antarctica 34

35 How do we work around this? Like I said earlier, almost everything in Ruby is an object All classes are instances of the Class class This means that classes are themselves objects class Person p Person.class #=> Class 35

36 Use Class Instance Variables Since classes are themselves objects, they can have their own instance variables We will refer to a class s instance variables as class instance variables Define class instance variables within the class definition body or within class methods with a Always use class instance variables, NEVER use class variables 36

37 Use Class Instance Variables class = 'EVERYWHERE' def class Penguin < = 'Antarctica' p Bird.location #=> "EVERYWHERE" p Penguin.location #=> "Antarctica 37

38 Classes Never Close Existing classes, including core classes, can be modified at any time just be declaring them my_string = 'hi' my_string.repeat(3) #=> NoMethodError class String def repeat(x) self * x p my_string.repeat(3) #=> "hihihi" This is dangerous and you should never do it unless you really know what you re doing 38

39 Modules I mentioned earlier that classes can inherit from only one class This seems really limiting at first, but that s where modules come in Modules are bundles of methods Declared with the module keyword Unlike classes, modules cannot be instantiated 39

40 Modules module MyModule def my_module_method 'Hello World' MyModule.new #=> NoMethodError 40

41 Mixing in Modules Modules get mixed into classes using include or ext Referred to as mix-ins When you mix a module into a class, that class gets access to all of the methods defined in that module 41

42 include vs. ext If you mix-in a module with: include: The module s methods will be available as instance methods ext: The module s methods will be available as class methods 42

43 Mixing in Modules module ClassMethodsModule def class_method 'Class Method' module InstanceMethodsModule def instance_method 'Instance Method' class MyClass ext ClassMethodsModule include InstanceMethodsModule p MyClass.class_method #=> "Class Method" p MyClass.new.instance_method #=> "Instance Method" 43

44 Separate Module Methods It should be clear if a method is meant to be an instance method or a class method It is extremely unlikely that a method is both Instance and class methods should be separated in the module with more, nested modules module MyModule module InstanceMethods def instance_method puts 'Instance Method' module ClassMethods def class_method puts 'Class Method' 44

45 Using Nested Modules The :: operator can be used to access a module in another module Thus, if a class wanted to access the module in the previous slide class MyClass include MyModule::InstanceMethods ext MyModule::ClassMethods MyClass.new.instance_method #=> "Instance Method" MyClass.class_method #=> "Class Method" 45

46 Requiring Files It's good practice for every class and module to have its own file To "import" other files, pass the path to the file without the extension as a string to the require method If the file foo.rb is in the same directory, put require './foo at the top of the file If it's in the parent directory, require '../foo Recall that requiring a file without the path imports a gem Note: "requiring" a file loads and runs that file 46

47 Homework 2 Homework 2 is released, it is designed to help you become more comfortable with Object Orientation You will be developing a workflow that you will see when we get to Rails 47

48 Homework 2 Passing a hash as an argument to a method def = = = params[:baz] 'Assigned foo, bar, and baz from params hash' p method_name(foo: 'foo', bar: 'bar', baz: 'baz') #=> "Assigned foo, bar, and baz from params hash" 48

Lecture 2. Object Orientation 1 / 50

Lecture 2. Object Orientation 1 / 50 Lecture 2 Object Orientation 1 / 50 Homework 1 Homework 1 was due last night You will be graded on: Correctness: 15 points (passing all RSpec tests) Style: 5 points (having no Rubocop style offenses) Best

More information

Lecture 2. Object Orientation 1 / 51

Lecture 2. Object Orientation 1 / 51 Lecture 2 Object Orientation 1 / 51 Homework 1 Homework 1 was due at noon You will be graded on: Correctness: 15 points (passing all RSpec tests) Style: 5 points (having no Rubocop style offenses) Best

More information

Lecture 1. Basic Ruby 1 / 61

Lecture 1. Basic Ruby 1 / 61 Lecture 1 Basic Ruby 1 / 61 What does this do? 3.times do print 'Hello, world!' end 2 / 61 Why Ruby? Optimized for programmer happiness Used for Ruby on Rails Very popular web framework 3 / 61 Course Policies

More information

Lecture 3. Miscellaneous Ruby and Testing 1 / 40

Lecture 3. Miscellaneous Ruby and Testing 1 / 40 Lecture 3 Miscellaneous Ruby and Testing 1 / 40 Homework 1 Grades were released! TAs provided feedback on best practices, but did not take off points Keep the comments in mind for future assignments! Any

More information

Lecture 4. Ruby on Rails 1 / 52

Lecture 4. Ruby on Rails 1 / 52 Lecture 4 Ruby on Rails 1 / 52 Homeworks 2 & 3 Grades were released for homework 2 Homework 3 was due last night Everyone got a style freebie since my default setup ignores spec files and I didn't change

More information

Ruby: Object-Oriented Concepts

Ruby: Object-Oriented Concepts Ruby: Object-Oriented Concepts Computer Science and Engineering College of Engineering The Ohio State University Lecture 8 Classes Classes have methods and variables class LightBulb # name with CamelCase

More information

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework Ruby logistics CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP Dan Grossman Autumn 2018 Next two sections use the Ruby language http://www.ruby-lang.org/ Installation / basic usage

More information

CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages CSc 372 Comparative Programming Languages 26 : Ruby Classes Christian Collberg collberg+372@gmail.com Department of Computer Science University of Arizona Copyright c 2008 Christian Collberg [1] Inheritance

More information

Lecture 3. Miscellaneous Ruby and Testing

Lecture 3. Miscellaneous Ruby and Testing Lecture 3 Miscellaneous Ruby and Testing 1 Sublime Text Guide I wrote a quick Sublime Text Guide that will help with Rubocop offenses It ll walk you through: Using spaces instead of tabs by default Using

More information

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP Dan Grossman Winter 2013 Ruby logistics Next two sections use the Ruby language http://www.ruby-lang.org/ Installation / basic usage

More information

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE 341, Autumn 2015, Ruby Introduction Summary CSE 341, Autumn 2015, Ruby Introduction Summary Disclaimer: This lecture summary is not necessarily a complete substitute for atting class, reading the associated code, etc. It is designed to be a useful

More information

Lecture 3. Miscellaneous Ruby and Testing 1 / 48

Lecture 3. Miscellaneous Ruby and Testing 1 / 48 Lecture 3 Miscellaneous Ruby and Testing 1 / 48 Homework 1 Grades were released! TAs provided feedback on best practices, but did not take off points Keep the comments in mind for future assignments! Any

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/ Administrative things Teaching assistant Brian Summa (bsumma @ seas.upenn.edu)

More information

CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages CSc 372 Comparative Programming Languages 28 : Ruby Classes Christian Collberg Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg November 1, 2011

More information

Inheritance. CSc 372. Comparative Programming Languages. 28 : Ruby Classes. Department of Computer Science University of Arizona.

Inheritance. CSc 372. Comparative Programming Languages. 28 : Ruby Classes. Department of Computer Science University of Arizona. Inheritance CSc 372 Comparative Programming Languages 28 : Ruby Classes Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg Let s start with this,

More information

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

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

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

Classes and Modules. Properties. Chapter 11

Classes and Modules. Properties. Chapter 11 Chapter 11 Classes and Modules In the previous chapters we have discussed the basics of the Ruby programming language, without looking at it from an object- oriented point of view. Object orientation is

More information

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2. Class #10: Understanding Primitives and Assignments Software Design I (CS 120): M. Allen, 19 Sep. 18 Java Arithmetic } Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = 2 + 5 / 2; 3.

More information

Programming Paradigms

Programming Paradigms PP 2016/17 Unit 4 Ruby Advanced 1/42 Programming Paradigms Unit 4 Ruby Advanced J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE PP 2016/17 Unit 4 Ruby Advanced 2/42 Outline

More information

SYMBOLS. you would not assign a value to a symbol: :name = "Fred" The Book of Ruby 2011 by Huw Collingbourne

SYMBOLS. you would not assign a value to a symbol: :name = Fred The Book of Ruby 2011 by Huw Collingbourne SYMBOLS Many newcomers to Ruby are confused by symbols. A symbol is an identifier whose first character is a colon (:), so :this is a symbol and so is :that. Symbols are, in fact, not at all complicated

More information

CS 105 Perl: Modules and Objects

CS 105 Perl: Modules and Objects CS 105 Perl: Modules and Objects February 20, 2013 Agenda Today s lecture is an introduction to Perl modules and objects, but first we will cover a handy feature Perl has for making data structures. Where

More information

S206E Lecture 19, 5/24/2016, Python an overview

S206E Lecture 19, 5/24/2016, Python an overview S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Global and local variables: differences between the two Global variable is usually declared at the start of the program, their

More information

Basic Object-Oriented Concepts. 5-Oct-17

Basic Object-Oriented Concepts. 5-Oct-17 Basic Object-Oriented Concepts 5-Oct-17 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains

More information

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1 ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1 Due to CMS by Tuesday, February 14. Social networking has caused a return of the dot-com madness. You want in on the easy money, so you have decided to make

More information

MITOCW watch?v=flgjisf3l78

MITOCW watch?v=flgjisf3l78 MITOCW watch?v=flgjisf3l78 The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To

More information

CSCI 161 Introduction to Computer Science

CSCI 161 Introduction to Computer Science CSCI 161 Introduction to Computer Science Department of Mathematics and Computer Science Lecture 2b A First Look at Class Design Last Time... We saw: How fields (instance variables) are declared How methods

More information

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

More information

CS1210 Lecture 28 Mar. 27, 2019

CS1210 Lecture 28 Mar. 27, 2019 CS1210 Lecture 28 Mar. 27, 2019 Discussion section exam scores posted score # people 0-5 6-10 11-15 16-20 21-25 26-30 28 48 39 37 30 9 median: 13 Some words about overall grades more detail next Wednesday

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

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Instance Variables if Statements Readings This Week s Reading: Review Ch 1-4 (that were previously assigned) (Reminder: Readings

More information

EECS 1001 and EECS 1030M, lab 01 conflict

EECS 1001 and EECS 1030M, lab 01 conflict EECS 1001 and EECS 1030M, lab 01 conflict Those students who are taking EECS 1001 and who are enrolled in lab 01 of EECS 1030M should switch to lab 02. If you need my help with switching lab sections,

More information

CSE 341: Programming Languages. Section AC with Nate Yazdani

CSE 341: Programming Languages. Section AC with Nate Yazdani CSE 341: Programming Languages Section AC with Nate Yazdani aga method dispatch mixins visitor pattern method dispatch what is dispatch method dispatch or just dispatch is the protocol to look up the method

More information

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10B Class Design By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Encapsulation Inheritance and Composition is a vs has a Polymorphism Information Hiding Public

More information

CS61A Lecture 20 Object Oriented Programming: Implementation. Jom Magrotker UC Berkeley EECS July 23, 2012

CS61A Lecture 20 Object Oriented Programming: Implementation. Jom Magrotker UC Berkeley EECS July 23, 2012 CS61A Lecture 20 Object Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012 COMPUTER SCIENCE IN THE NEWS http://www.theengineer.co.uk/sectors/electronics/news/researchers

More information

15.1 Origins and Uses of Ruby

15.1 Origins and Uses of Ruby 15.1 Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in 1996 - Use spread rapidly in Japan - Use is now growing in part because of its use in Rails - A pure object-oriented purely interpreted

More information

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern CSE 399-004: Python Programming Lecture 12: Decorators April 9, 200 http://www.seas.upenn.edu/~cse39904/ Announcements Projects (code and documentation) are due: April 20, 200 at pm There will be informal

More information

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Creating Your Own Class Lecture 7 Readings This Week s Reading: Ch 3.1-3.8 (Major conceptual jump) Next Week: Review Ch 1-4 (that

More information

Array variable in class ruby. Array variable in class ruby.zip

Array variable in class ruby. Array variable in class ruby.zip Array variable in class ruby Array variable in class ruby.zip Returns a new array. In the first form, if no arguments are sent, the new array will be empty. When a size and an optional obj are sent, an

More information

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7 Administration Classes CS 99 Summer 2000 Michael Clarkson Lecture 7 Lab 7 due tomorrow Question: Lab 6.equals( SquareRoot )? Lab 8 posted today Prelim 2 in six days! Covers two weeks of material: lectures

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 31 Static Members Welcome to Module 16 of Programming in C++.

More information

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון 22 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static, compile time representation of object-oriented

More information

And Even More and More C++ Fundamentals of Computer Science

And Even More and More C++ Fundamentals of Computer Science And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Special Members Friendship Classes are an expanded version of data structures (structs) Like structs, the hold data members

More information

Lecture 10. Overriding & Casting About

Lecture 10. Overriding & Casting About Lecture 10 Overriding & Casting About Announcements for This Lecture Readings Sections 4.2, 4.3 Prelim, March 8 th 7:30-9:30 Material up to next Tuesday Sample prelims from past years on course web page

More information

Programming Exercise 14: Inheritance and Polymorphism

Programming Exercise 14: Inheritance and Polymorphism Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.

More information

CS/ENGRD 2110 FALL Lecture 2: Objects and classes in Java

CS/ENGRD 2110 FALL Lecture 2: Objects and classes in Java 1 CS/ENGRD 2110 FALL 2017 Lecture 2: Objects and classes in Java http://courses.cs.cornell.edu/cs2110 CMS VideoNote.com, PPT slides, DrJava 2 CMS. Visit course webpage, click Links, then CMS for 2110.

More information

CS 390 Software Engineering Lecture 6 Ruby

CS 390 Software Engineering Lecture 6 Ruby CS 390 Software Engineering Lecture 6 Ruby References: Ruby in Twenty Minutes, available at https://www.ruby-lang.org/en/documentation/quickstart/. Outline Clone Ruby example git repository $ git clone

More information

Week 3 Classes and Objects

Week 3 Classes and Objects Week 3 Classes and Objects written by Alexandros Evangelidis, adapted from J. Gardiner et al. 13 October 2015 1 Last Week Last week, we looked at some of the different types available in Java, and the

More information

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות 2 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static,

More information

COMP 250 Winter 2011 Reading: Java background January 5, 2011

COMP 250 Winter 2011 Reading: Java background January 5, 2011 Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP

More information

Overview of the Ruby Language. By Ron Haley

Overview of the Ruby Language. By Ron Haley Overview of the Ruby Language By Ron Haley Outline Ruby About Ruby Installation Basics Ruby Conventions Arrays and Hashes Symbols Control Structures Regular Expressions Class vs. Module Blocks, Procs,

More information

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.

More information

Readings for This Lecture

Readings for This Lecture Lecture 4 Classes Readings for This Lecture Section 1.4, 1.5 in text Section 3.1 in text Plive activities referenced in the text Please look at lecture summaries online Handouts are short version Presentation

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

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Ruby. Mooly Sagiv. Most slides taken from Dan Grossman

Ruby. Mooly Sagiv. Most slides taken from Dan Grossman Ruby Mooly Sagiv Most slides taken from Dan Grossman Ruby dynamic, reflective, object-oriented, general-purpose programming language Designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto

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

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

Notes on Chapter Three

Notes on Chapter Three Notes on Chapter Three Methods 1. A Method is a named block of code that can be executed by using the method name. When the code in the method has completed it will return to the place it was called in

More information

Inheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming.

Inheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming. Inheritance in Ruby You are familiar with the idea of inheritance and how to use this in programming. In this introduction, I'll describe inheritance in Ruby from scratch. Much of this material should

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

Survey #2. Programming Assignment 3. Final Exam. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Survey #2. Programming Assignment 3. Final Exam. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Accessing the Superclass Object Hierarchies is-a, has-a Readings This Week: Ch 9.4-9.5 and into Ch 10.1-10.8 (Ch 11.4-11.5 and into

More information

Principles of Object Oriented Programming. Lecture 4

Principles of Object Oriented Programming. Lecture 4 Principles of Object Oriented Programming Lecture 4 Object-Oriented Programming There are several concepts underlying OOP: Abstract Types (Classes) Encapsulation (or Information Hiding) Polymorphism Inheritance

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

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012 COMPUTER SCIENCE IN THE NEWS CS6A Lecture 2 Scheme Jom Magrotker UC Berkeley EECS July 24, 202 http://spectrum.ieee.org/tech talk/robotics/artificial intelligence/a texas hold em tournament for ais 2 TODAY

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

1B1b Classes in Java Part I

1B1b Classes in Java Part I 1B1b Classes in Java Part I Agenda Defining simple classes. Instance variables and methods. Objects. Object references. 1 2 Reading You should be reading: Part I chapters 6,9,10 And browsing: Part IV chapter

More information

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

More information

Lecture 02, Fall 2018 Friday September 7

Lecture 02, Fall 2018 Friday September 7 Anatomy of a class Oliver W. Layton CS231: Data Structures and Algorithms Lecture 02, Fall 2018 Friday September 7 Follow-up Python is also cross-platform. What s the advantage of Java? It s true: Python

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static, compile time representation of object-oriented

More information

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

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters) Classes Classes/Objects/Interfaces (Savitch, Various Chapters) TOPICS Classes Public versus Private Static Data Static Methods Interfaces Classes are the basis of object-oriented (OO) programming. They

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

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

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 Review What is the difference between a while loop and an if statement? What is an off-by-one

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

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

Import Statements, Instance Members, and the Default Constructor

Import Statements, Instance Members, and the Default Constructor Import Statements, Instance Members, and the Default Constructor Introduction In this article from my free Java 8 course, I will be discussing import statements, instance members, and the default constructor.

More information

Sixth lecture; classes, objects, reference operator.

Sixth lecture; classes, objects, reference operator. Sixth lecture; classes, objects, reference operator. 1 Some notes on the administration of the class: From here on out, homework assignments should be a bit shorter, and labs a bit longer. My office hours

More information

Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods

Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods Today CSE341: Programming Languages Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins Alan Borning Spring 2018 Dynamic dispatch aka late binding aka virtual method calls Call to self.m2() in

More information

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects CS256 Computer Science I Kevin Sahr, PhD Lecture 11: Objects 1 Programs as Models remember: we write programs to solve realworld problems programs act as models of the real-world problem to be solved one

More information

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu Physics 2660: Fundamentals of Scientific Computing Lecture 3 Instructor: Prof. Chris Neu (chris.neu@virginia.edu) Announcements Weekly readings will be assigned and available through the class wiki home

More information

In fact, as your program grows, you might imagine it organized by class and superclass, creating a kind of giant tree structure. At the base is the

In fact, as your program grows, you might imagine it organized by class and superclass, creating a kind of giant tree structure. At the base is the 6 Method Lookup and Constant Lookup As we saw in Chapter 5, classes play an important role in Ruby, holding method definitions and constant values, among other things. We also learned how Ruby implements

More information

Basics Inheritance and Instance Variables Inheritance and Methods Class Variables. Ruby Inheritance CSCI September 2017.

Basics Inheritance and Instance Variables Inheritance and Methods Class Variables. Ruby Inheritance CSCI September 2017. CSCI400 05 September 2017 Color Key Clickable URL link Write down an answer to this for class participation Just a comment don t confuse with yellow Class Participation Get out a piece of paper, we ll

More information

CS 5142 Scripting Languages

CS 5142 Scripting Languages CS 5142 Scripting Languages 10/25/2012 Ruby 1 Outline Ruby Martin Hirzel 2 About Ruby Invented 1995 by Yokihiro Matz Matsumoto Influenced by SmallTalk Everything is an object (even e.g., integers) Blocks

More information

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java 1 CS/ENGRD 2110 SPRING 2014 Lecture 2: Objects and classes in Java http://courses.cs.cornell.edu/cs2110 Java OO (Object Orientation) 2 Python and Matlab have objects and classes. Strong-typing nature of

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: 1 Date:

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 in Java. Topic : Objects and Classes (cont) Object Oriented Design

Object-Oriented Programming in Java. Topic : Objects and Classes (cont) Object Oriented Design Electrical and Computer Engineering Object-Oriented in Java Topic : Objects and Classes (cont) Object Oriented Maj Joel Young Joel.Young@afit.edu 11-Sep-03 Maj Joel Young Using Class Instances Accessing

More information

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects Administrative Stuff September 12, 2007 HW3 is due on Friday No new HW will be out this week Next Tuesday we will have Midterm 1: Sep 18 @ 6:30 7:45pm. Location: Curtiss Hall 127 (classroom) On Monday

More information

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to A PROGRAM IS A SEQUENCE of instructions that a computer can execute to perform some task. A simple enough idea, but for the computer to make any use of the instructions, they must be written in a form

More information

CS 134 Programming Exercise 3:

CS 134 Programming Exercise 3: CS 134 Programming Exercise 3: Repulsive Behavior Objective: To gain experience implementing classes and methods. Note that you must bring a program design to lab this week! The Scenario. For this lab,

More information

Chapter 2: Java OOP I

Chapter 2: Java OOP I Chapter 2: Java OOP I Yang Wang wyang AT njnet.edu.cn Outline OO Concepts Class and Objects Package Field Method Construct and Initialization Access Control OO Concepts Object Oriented Methods Object An

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 16 Classes Prof. Jeremy Dixon Based on slides from http://www.csee.umbc.edu/courses/691p/notes/python/python3.ppt Last Class We Covered Review of Functions

More information

file:///users/dave/tmp/rubyadv/html/metaprogramming.html

file:///users/dave/tmp/rubyadv/html/metaprogramming.html Page 1 of 13 Metaprogramming Object state behavior Me, Me, Me First, understand self self self is the current object Default receiver for method calls with no receiver Place where instance variables are

More information

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6 More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6 Ziad Matni Dept. of Computer Science, UCSB Administrative CHANGED T.A. OFFICE/OPEN LAB

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit. Com S 227 Fall 2017 Miniassignment 1 50 points Due Date: Monday, October 16, 11:59 pm (midnight) Late deadline (25% penalty): Tuesday, October 17, 11:59 pm General information This assignment is to be

More information

Classes. Classes as Code Libraries. Classes as Data Structures

Classes. Classes as Code Libraries. Classes as Data Structures Classes Classes/Objects/Interfaces (Savitch, Various Chapters) TOPICS Classes Public versus Private Static Data Static Methods Interfaces Classes are the basis of object-oriented (OO) programming. They

More information