Ruby II. Classes. Classes are straight forward in Ruby.

Size: px
Start display at page:

Download "Ruby II. Classes. Classes are straight forward in Ruby."

Transcription

1 Ruby II Classes Classes are straight forward in Ruby. expr Note that the class name begins with a capitol letter. Classes can contain instance variables, instance methods, class variables, class methods, and special accessor functions. Classes Instance Attributes/Methods Instance attributes and methods are variables and methods that belong to the object. Instance methods are simply methods defined inside of a class structure. Instance attributes are variables whose name begins with that are used in an instance method. It is not possible to declare instance attributes outside of the instance methods. If an instance attribute is accessed before it is set, the value is nil. 1

2 Classes Instance Attributes/Methods def = 0 def += amount myaccount = BankAccount.new() myaccount.depositfunds(100) In this example, the class is BankAccount, depositfunds is an instance method of BankAccount, is an instance attribute of BankAccount. We call the method after we create an object of type BankAccount. Classes Initialize Method You must create an object named initialize for each class you create. When you create a new object, you call the new method for the class. myaccount = BankAccount.new(500); The new method will create the object and then call the user defined initialize method in the class. Any parameters passed to new will be passed to the initialize method. Because you do not declare instance attributes ahead of time in Ruby, the initialize method is a good place to set up all instance attributes. Classes Initialize Cont. def initialize(startingbalance, accounttype= Checking, = = = accountnumber Initialize can only be declared once per class. If you wish to have optional parameters, you should set the default values in the parameter list. 2

3 Classes - Self An instance method is able to call another instance method. If you do not specify an object to be the receiver, it is assumed that the current object is the receiver. def transfermoney(receivingaccount, amount) withdrawfunds(amount) receivingaccount.depositfunds(amount) In this case, we did not specify a receiver for withdrawfunds, so the current object was passed. To make the code more clear, we could have used the self keyword. self simply refers to the current object. self.withdrawfunds(amount) Classes Access Control Instance variables are always private. You must use a method to allow get/set privileges from outside of the class. All instance methods besides initialize are public by default. initialize is always private. Though in some ways not really since new invokes it implicitly It is possible to change the access level of instance methods by specifying public, protected, or private. public: can be called by anyone private: can only be called by the current object. This means that you can not specify a receiver. protected: can by called in the class/subclass. Differs from private because you can specify a reciever. Classes Access Control cont. There are two ways to specify accessibility. #1) Write the accessibility level followed by a newline. Any subsequent methods will have that level. In the following definition, withdrawfunds is protected and the other methods are public. protected def -= amount public def += amount def transfermoney(receivingaccount, amount) receivingaccount.depositfunds(amount) withdrawfunds(amount) 3

4 Classes Access Control cont. #2) Declare all methods and then call the access levels with parameters passed to them. The parameter should be : + methodname. Any method name specified will have that access level. def -= amount def += amount def transfermoney(receivingaccount, amount) receivingaccount.depositfunds(amount) withdrawfunds(amount) protected :withdrawfunds, :depositfunds public :transfermoney Classes Attribute Accessors As mentioned before, instance attributes are always private. You can not specify public or protected for them. You must create get/set methods for the attributes if you want them to be accessed outside of the class. def balance def = amount This could get tedious, so Ruby has made it much simpler to create these get/set methods with accessors. Classes Attribute Accessors Ruby offers three accessor methods to do the basic get/set for you. attr_reader: Implements the get behavior. attr_writer: Implements the set behavior. attr_accessor: Implements both get & set. All of these are used by specifying the proper method and then passing it a colon and the instance attribute s name. You can specify multiple attributes by separating the names with a comma. attr_reader :balance attr_writer :balance, :accounttype attr_accessor :balance Once you set these accessor methods, you can access the attribute just as you would if it were public. myaccount.balance = 100 puts myaccount.balance 4

5 Classes Virtual Attributes It is possible to allow the user to assign to an attribute that does not exist. myaccount.interestratepercent = 10 Then in the class, we can handle the incoming value and set interestrate appropriately. Note the equal sign at the of the method name. def interestratepercent= = (percentage.to_f/100.to_f).to_f Classes Class Variable A class variable is shared among all the instances of a class. It is useful if you want to keep a balance/count of all instances. A class variable MUST be initialized in the class outside of any methods. A class variable is specified by The class variable is accessible in the instance methods and the class = 0 def -= -= amount Classes Class Methods A class method is a method for the class instead of the instance. A class method has no access to the instance attributes except through an object of the class. The class method is defined inside of the class. It apps the class name to it s definition def BankAccount.transferFunds(fromAccount, toaccount, amount) fromaccount.withdrawfunds(amount) toaccount.depositfunds(amount) Note that withdrawfunds and depositfunds must be public in order for this to work. 5

6 Classes Singleton Classes We can use class methods to create a singleton class in Ruby. In this example, we will limit the creation of Myself to a single object. We first disable the new method. We can do this by setting it to private. This way, we can control when new gets called and therefore how many objects are created of our class. It is possible to set an existing item to private by using the private_class_method method. We pass the method a colon followed by the name of the method we want to set to be private (in this case, new ) class Myself private_class_method :new Classes Singleton Classes cont. Next we create a new constructor (make) for the user to call. Our new constructor will decide to call new or not. We use a class method for our constructor and a class variable to store the actual object. If the object is not created yet, we can create it by calling new. Otherwise, we can just return the already existing object. class Myself private_class_method = nil def = thomas = Myself.make() print thomas.inspect() thomasclone = Myself.make() print thomasclone.inspect() Classes Inspect & to_s Two useful methods for testing are inspect and to_s. inspect lists the object s instance variables. @accountnumber=4654> to_s converts the object to a string. myaccount.to_s() #<BankAccount:0x27b72f8> We can overwrite to_s to present a more readable string. def to_s "Balance for #{@accounttype} Account ##{@accountnumber}: $#{@balance}" Balance for Checking Account #4654: $500 6

7 Classes - Inheritance When an object oriented language is implementing inheritance, it must decide if it will allow single inheritance, multiple inheritance, or some sort of hybrid. In life, multiple inheritance makes sense. Single inheritance limits object oriented programming. However, multiple inheritance can get very messy. There can be ambiguous attributes and it is difficult to read and maintain. Ruby implements single inheritance. An object can only have one parent. However, it creates a hybrid by allowing mixins to include additional functionality We will study mixins when we look at modules. Classes - Inheritance When declaring a class with a parent, we simply add < parentname to the of the class declaration class CheckingAccount < BankAccount expr A child class will inherit all of the parent s attributes and methods no matter what the access level. It is possible for a child class to overwrite any of the parent s methods. class CheckingAccount < BankAccount attr_accessor :pin def to_s PIN for Account ##{@accountnumber}: #{@pin}" Classes - Inheritance Notice that we did not create a new initialize method for CheckingAccount. When we call CheckingAccount.new(), Ruby will first see if CheckingAccount has an initialize function. When it does not find one, it will check the parent and see if the parent has one. This is how it behaves with all methods. Note there is obviously a top Object class just like in JavaScript that is the ultimate super class for everything If wanted to add additional fields to our initialization, we could create our own initialize. class CheckingAccount < BankAccount def initialize(startingbalance, pin, = = = = accountnumber 7

8 Classes - Super Instead of repeating the initialize code we use in BankAccount, we should just pass the appropriate parameters to the BankAccount initialize. We use the keyword super to access the parent methods. class CheckingAccount < BankAccount def initialize(startingbalance, pin, accountnumber=nil) super(startingbalance, Checking, = pin Modules A module is a collection of classes, methods, and constants. Since modules can be stored in separate files with their own namespace and included (and mixed in) when needed, they are ideal for reusability. module Bank expr This module creates a namespace named Bank with our BankAccount class in it. Modules cont. There are various ways to access the objects in the module. You put constants and classes in the module the same way you would put it in a normal file. module Logs LOGPATH = /logs class LogFile In order to reference a constant or a class inside of a module, you must use the scope resolution operator (::) path = Logs::LOGPATH newfile = Logs::LogFile.new() 8

9 Modules cont. Methods in modules are private by default. In order to make them public, you must name the method like you would a class method: ModuleName.methodname module Logs def Logs.addLog(logmessage) expr Then you can call the method simply by calling the same name Logs.addLog( Success ) Modules - Mixins As mentioned in the classes section, we use modules to get around the need for multiple inheritance. As we saw in the last section, we had to declare methods with the module name in front of it in order to access it outside of the module. If we declare methods without the module name module Logs def addlog(logmessage) expr Logs.addLog( Success ) We get the following error: undefined method `addlog' for Logs:Module Modules - Mixins In this case, addlog is being implemented as an instance method and because a module is not a class, it can not use an instance method. However, we can mix-in the module with a class and then the class will have access to the instance method. include Logs Now, the BankAccount class can use addlog as if it were an instance method in BankAccount. myaccount = BankAccount.new myaccount.addlog( success ) If multiple mixins contain the same method name, the last one to be included is the method that will be used. 9

10 Modules Mixins cont. Mixin methods can call other methods in the class. Of course, the class must ensure that it defines any methods that the included mixin calls. module Logs def addlog(logmessage) puts self.getaccount + : + logmessage include Logs def getaccount return #{@accounttype} Account ##{@accountnumber} myaccount = BankAccount.new myaccount.addlog( success ) Modules Mixins cont. Mixins can access/set instance attributes in the same manner as methods. module Logs attr_reader :logsadded def = true include Logs myaccount = BankAccount.new myaccount.addlog( success ) puts myaccount.logsadded Note: The same possible conflict does exist if two included mixins contain the same attribute name. Hmmm you kind of wonder if this really doesn t have the same types of problems of multiple inheritance 10

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

CSE 341: Programming Languages

CSE 341: Programming Languages CSE 341: Programming Languages Hal Perkins Spring 2011 Lecture 19 Introduction to Ruby Hal Perkins CSE341 Spring 2011, Lecture 19 1 Today Why Ruby? Some basics of Ruby programs Syntax Classes, Methods

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

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

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

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

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

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

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

More information

A A B U n i v e r s i t y

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

Strings and Variables

Strings and Variables Strings and Variables class Player attr_accessor :name attr_reader :health def initialize(name, health=100) @name = name.capitalize @health = health @found_treasures = Hash.new(0) Inside the initialize

More information

Inheritance Ch

Inheritance Ch Inheritance Ch 15.1-15.2 Announcements Test graded! Highlights - Creating parent/child classes (inheritance) -protected Story time Story time Story time Story time Story time Derived classes Let's make

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

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80)

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80) A Bit of History Some notable examples of early object-oriented languages and systems: Sketchpad (Ivan Sutherland s 1963 PhD dissertation) was the first system to use classes and instances (although Sketchpad

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

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

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Chapter 10 Defining Classes

Chapter 10 Defining Classes Chapter 10 Defining Classes What Is a Class? A class is a data type whose variables are objects Some pre-defined data types you have used are int char You can define your own classes define your own types

More information

Multiple Inheritance using modules in Ruby

Multiple Inheritance using modules in Ruby Computer Science and Engineering IIT Bombay {amruta}@cse.iitb.ac.in November 29, 2004 Introduction Ruby is an interpreted scripting language for quick and easy object-oriented programming Important Features

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 2. Object Orientation

Lecture 2. Object Orientation Lecture 2 Object Orientation 1 Homework 0 Grades Homework 0 grades were returned earlier this week Any questions? 2 Homework 1 Homework 1 is due tonight at 11:59pm You will be graded on: Correctness: 15

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

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

Last lecture. Lecture 9. in a nutshell. in a nutshell 2. Example of encapsulation. Example of encapsulation. Class test. Procedural Programming

Last lecture. Lecture 9. in a nutshell. in a nutshell 2. Example of encapsulation. Example of encapsulation. Class test. Procedural Programming 1 Lecture 9 Last lecture Class test Has been marked Collect your marks at your next seminar Seminars There are seminars this week to go through the class test Meet in the classroom indicated on the timetable

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

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 1. Introduction 2. Objects and classes 3. Information hiding 4. Constructors 5. Some examples of Java classes 6. Inheritance revisited 7. The class hierarchy

More information

Introduction to Ruby. Part I

Introduction to Ruby. Part I Introduction to Ruby Sebastian Fischer Part I Data Numbers, Strings, Ranges, Arrays/Hashes Control Branching, Loops, Iterators Numbers >> 42 => 42 >> -17 => -17 >> 1.23 => 1.23 >> 4.56e7 => 45600000.0

More information

Encapsulation. Mason Vail Boise State University Computer Science

Encapsulation. Mason Vail Boise State University Computer Science Encapsulation Mason Vail Boise State University Computer Science Pillars of Object-Oriented Programming Encapsulation Inheritance Polymorphism Abstraction (sometimes) Object Identity Data (variables) make

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

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public

More information

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class Chapter 6 Inheritance Extending a Class Introduction; Need for Inheritance; Different form of Inheritance; Derived and Base Classes; Inheritance and Access control; Multiple Inheritance Revisited; Multilevel

More information

1. BlueJ bank example with subclasses of BankAccount 2. Transparency of UML diagram for BankAccount class hierarchy

1. BlueJ bank example with subclasses of BankAccount 2. Transparency of UML diagram for BankAccount class hierarchy CS112 Lecture: Fundamental Concepts of Object-Oriented Software Development Last revised 1/13/04 Objectives: 1. To review/introduce key concepts of object-orientation: object, class, data members (class

More information

Objects and Iterators

Objects and Iterators Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a

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

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

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

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. QUIZ How

More information

STUDENT LESSON A5 Designing and Using Classes

STUDENT LESSON A5 Designing and Using Classes STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of

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

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public

More information

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341 CSE 413 Spring 2011 Introduction to Ruby Credit: Dan Grossman, CSE341 Why? Because: Pure object-oriented language Interesting, not entirely obvious implications Interesting design decisions Type system,

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

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

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. Ch. 14: Inheritance

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use

More information

About Ruby Comments Constants and variables Scopes Methods Ranges Arrays Operators Flow Control Iterators Math Library Date and Time Hashes Object

About Ruby Comments Constants and variables Scopes Methods Ranges Arrays Operators Flow Control Iterators Math Library Date and Time Hashes Object October 14,2014 About Ruby Comments Constants and variables Scopes Methods Ranges Arrays Operators Flow Control Iterators Math Library Date and Time Hashes Object and Classes Conclusion Hmw 2 created by

More information

Unit Title: Objects in Visual Basic.NET. Software Development Unit 4. Objects in Visual Basic.NET

Unit Title: Objects in Visual Basic.NET. Software Development Unit 4. Objects in Visual Basic.NET Software Development Unit 4 Objects in Visual Basic.NET Aims This unit proceeds to the heart of object-oriented programming, introducing the mechanisms for creating new classes of object, defining their

More information

Simplest version of DayOfYear

Simplest version of DayOfYear Reminder from last week: Simplest version of DayOfYear class DayOfYear { public: void output(); int month; int day; }; Like a struct with an added method All parts public Clients access month, day directly

More information

PART A : MULTIPLE CHOICE Circle the letter of the best answer (1 mark each)

PART A : MULTIPLE CHOICE Circle the letter of the best answer (1 mark each) PART A : MULTIPLE CHOICE Circle the letter of the best answer (1 mark each) 1. An example of a narrowing conversion is a) double to long b) long to integer c) float to long d) integer to long 2. The key

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

Handout 9 OO Inheritance.

Handout 9 OO Inheritance. Handout 9 CS603 Object-Oriented Programming Fall 2016 Page 1 of 11 Handout 9 OO Inheritance. All classes in Java form a hierarchy. The top of the hierarchy is class Object Example: classicalarchives.com

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

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

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

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

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

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

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

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

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

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int, Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class

More information

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Singleton Pattern Mar. 13, 2007 What is it? If you need to make sure that there can be one and only one instance of a class. For example,

More information

CS162 Week 1. Kyle Dewey. Friday, January 10, 14

CS162 Week 1. Kyle Dewey. Friday, January 10, 14 CS162 Week 1 Kyle Dewey Overview Basic Introduction CS Accounts Scala survival guide Office Hour Choose an hour from within: Tuesday/Thursday 11 AM - 1 PM Friday 11 AM - 4 PM Also available by appointment

More information

Ruby, with foxes. Ruby, cont d. Warning. why's (poignant) Guide to Ruby

Ruby, with foxes. Ruby, cont d. Warning. why's (poignant) Guide to Ruby O Ruby, cont d n O Ruby, with foxes n why's (poignant) Guide to Ruby Ruby explained through humorous and more or less irrelevant stories about foxes, elfs, cats and others Warning If I was put off Ruby

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

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

Principles of Ruby Applica3on Design. Dean Wampler Senior Mentor and Consultant Object Mentor, Inc. Chicago, IL

Principles of Ruby Applica3on Design. Dean Wampler Senior Mentor and Consultant Object Mentor, Inc. Chicago, IL Principles of Ruby Applica3on Design Dean Wampler Senior Mentor and Consultant Object Mentor, Inc. Chicago, IL dean@objectmentor.com 1 Get the latest version of this talk: aspectprogramming.com/papers

More information

Ruby on Rails for PHP and Java Developers

Ruby on Rails for PHP and Java Developers Ruby on Rails for PHP and Java Developers Bearbeitet von Deepak Vohra 1. Auflage 2007. Taschenbuch. xvi, 394 S. Paperback ISBN 978 3 540 73144 3 Format (B x L): 15,5 x 23,5 cm Gewicht: 629 g Weitere Fachgebiete

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

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill Chapter 12 OOP: Creating Object-Oriented Programs McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter Objectives - 1 Use object-oriented terminology correctly Create a two-tier

More information

Lecture Notes on Programming Languages

Lecture Notes on Programming Languages Lecture Notes on Programming Languages 85 Lecture 09: Support for Object-Oriented Programming This lecture discusses how programming languages support object-oriented programming. Topics to be covered

More information

CLASSES AND OBJECTS IN JAVA

CLASSES AND OBJECTS IN JAVA Lesson 8 CLASSES AND OBJECTS IN JAVA (1) Which of the following defines attributes and methods? (a) Class (b) Object (c) Function (d) Variable (2) Which of the following keyword is used to declare Class

More information

Intermediate Cucumber. CSCI 5828: Foundations of Software Engineering Lecture 17 03/13/2012

Intermediate Cucumber. CSCI 5828: Foundations of Software Engineering Lecture 17 03/13/2012 Intermediate Cucumber CSCI 5828: Foundations of Software Engineering Lecture 17 03/13/2012 1 ReadyTalk Recruiting Event The ACM Student Chapter is hosting a recruiting event by a local Denver start-up

More information

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 Contents 1 Mutation in the Doghouse 1 1.1 Aside: Access Modifiers..................................

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

Inheritance: Definition

Inheritance: Definition Inheritance 1 Inheritance: Definition inheritance: a parent-child relationship between classes allows sharing of the behavior of the parent class into its child classes one of the major benefits of object-oriented

More information

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance? CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Storing Data in Objects

Storing Data in Objects Storing Data in Objects Rob Miles Department of Computer Science 28d 08120 Programming 2 Objects and Items I have said for some time that you use objects to represent things in your problem Objects equate

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

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

CSC Web Programming. Introduction to JavaScript

CSC Web Programming. Introduction to JavaScript CSC 242 - Web Programming Introduction to JavaScript JavaScript JavaScript is a client-side scripting language the code is executed by the web browser JavaScript is an embedded language it relies on its

More information

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package access control To

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming In C++ classes provide the functionality necessary to use object-oriented programming OOP is a particular way of organizing computer programs It doesn t allow you to do anything

More information

Programming Languages

Programming Languages Programming Languages Dr. Michael Petter WS 2016/17 Exercise Sheet 8 Assignment 8.1 Quiz 1. Can Smalltalk Inheritance be used to model Java s inheritance? What about attribute access? 2. In a Trait-based

More information

6.096 Introduction to C++

6.096 Introduction to C++ MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. MASSACHUSETTS INSTITUTE

More information

Project 5 Due 11:59:59pm Wed, Nov 25, 2015 (no late submissions)

Project 5 Due 11:59:59pm Wed, Nov 25, 2015 (no late submissions) Introduction Project 5 Due 11:59:59pm Wed, Nov 25, 2015 (no late submissions) In this project, you will write a compiler for a programming language called Rube, which is a small objectoriented programming

More information

Arrays Classes & Methods, Inheritance

Arrays Classes & Methods, Inheritance Course Name: Advanced Java Lecture 4 Topics to be covered Arrays Classes & Methods, Inheritance INTRODUCTION TO ARRAYS The following variable declarations each allocate enough storage to hold one value

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

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

1 State, objects, and abstraction

1 State, objects, and abstraction 6.01, Spring Semester, 2008 Course notes for Week 4 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.01 Introduction to EECS I Spring Semester, 2008 Course

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Java Puzzle Ball Nick Ristuccia

Java Puzzle Ball Nick Ristuccia Java Puzzle Ball Nick Ristuccia Lesson 2-3 Editing Java Code You've seen Static Variables Red Bumpers start with an orientation of 0. public class RedBumper { private static Color color = Color.RED; private

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

comparing groovy & jruby *

comparing groovy & jruby * ThoughtWorks comparing groovy & jruby * * please check all knives, guns, pitchforks, and torches at the door NEAL FORD software architect / meme wrangler ThoughtWorks nford@thoughtworks.com 3003 Summit

More information

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

Symbols. accessor properties, attributes, creating, adding properties, 8 anonymous functions, 20, 80

Symbols. accessor properties, attributes, creating, adding properties, 8 anonymous functions, 20, 80 Index Symbols { } (braces) for function contents, 18 and object properties, 9 == (double equals operator), 5 === (triple equals operator), 5 [ ] (square brackets) for array literals, 10 for property access,

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information