Variables All variables hold object references

Slides:



Advertisements
Similar presentations
PHP functions What are Functions? A function structure:
Advertisements

Python Objects and Classes
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
And other languages….  Get out a piece of paper  You’ll be tracing some code (quick exercises) as we go along.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
Introduction to Ruby CSE 413 Autumn 2008 Credit: Dan Grossman, CSE341.
Ruby (on Rails) CSE 190M, Spring 2009 Week 4. Constructors Writing a new class is simple! Example: class Point end But we may want to initialize state.
Ruby (on Rails) Slides modified by ements-2ed.shtml) 1.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Inheritance in the Java programming language J. W. Rider.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Constructors & Garbage Collection Ch. 9 – Head First Java.
Ruby Objects, Classes and Variables CS 480/680 – Comparative Languages.
Chapter 5 Introduction to Defining Classes
Object-Oriented Programming Chapter Chapter
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
ISBN Object-Oriented Programming Chapter Chapter
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Classes, Interfaces and Packages
21. PHP Classes To define a class, use the keyword class followed by the name and a block with the properties and method definitions Properties are declared.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Design issues for Object-Oriented Languages
Ruby Inheritance and other languages….
Topic: Classes and Objects
Java Yingcai Xiao.
Inheritance ITI1121 Nour El Kadri.
Java Primer 1: Types, Classes and Operators
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Types of Programming Languages
Programming Language Concepts (CIS 635)
Classes, Objects, And Variables
CS 302 Week 11 Jim Williams, PhD.
Chapter 9 Inheritance and Polymorphism
Corresponds with Chapter 7
Java Programming Language
Chapter 9: Polymorphism and Inheritance
Object-Oriented Programming in PHP
Object-Oriented Programming
Java Programming Language
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
Corresponds with Chapter 5
Presentation transcript:

Variables All variables hold object references Similar to Java handles, but in Ruby there are no primitives Like Java, objects are garbage collected

Variable Scope Constants – defined in a class or a module can be accessed unadorned anywhere within the class or module; outside, they can be accessed using scope :: operator Constants defined outside of a class or module can be accessed unadorned Global variables (declared outside any class or module) are available throughout a program Class variables can only be accessed within the class (or module); but, you can provide accessor methods Ruby Notes

Variable Scope Instance variables can only be accessed within the class or subclasses (but you can make them attributes or provide accessor methods) Local variables – scope is the immediately enclosing block, method definition, class definition, module definition or top level program Method parameters are variables local to the method Ruby Notes

Parameter Passing all variables are references to objects parameters are passed by value (references are passed by value) – some mistakenly call this pass by reference Ruby Notes

Parameter Passing Example #!/usr/local/bin/ruby def increment(n) n = n + 1; end def zero(array) n = array.length - 1; n.downto(0) do |i| array[i] = 0; def anotherzero(array) newarray = Array.new(array.length); n = newarray.length - 1; newarray[i] = 0; array = newarray; n = 3; increment(n); puts n.to_s; array = [1, 2, 3]; zero(array); puts array.join(", "); anotherzero(array); What is the output? http://www.cs.appstate.edu/~can/classes/3490/Ruby/callbyval.rb Ruby Notes

Variable scope and parameter passing example #!/usr/local/bin/ruby msg = "hello"; agent = 99; def foo(msg, agent) puts msg + " " + agent.to_s; msg = "bye" agent += 1; msg.upcase!; end foo(msg, agent) What is the output? http://www.cs.appstate.edu/~can/classes/3490/Ruby/scope.rb Ruby Notes

Block Scope Example #!/usr/local/bin/ruby def foo(localvar1) localvar2.downto(1) do |blockvar| puts "#{localvar1} #{localvar2} #{blockvar}" end foo(3) What is the output? http://www.cs.appstate.edu/~can/classes/3490/Ruby/blockscope.rb Ruby Notes

Ruby classes Constructor method is called initialize Objects are created by executing call: var = Classname.new(parameter(s)) initialize method automatically called and receives parameters passed to new Parameters are local to the initialize method var is a reference to an object (not an actual object) Ruby Notes

Classes Class definition used to create a new class or extend an existing class class String #whatever I define here is added to #the existing String class end Executing a class definition causes a Class object to be created and assigned to a constant called classname the class definition above causes: String = Class.new(); Ruby Notes

Methods Instead of saying “method call,” Ruby types refer to this process as sending a message to a receiver stk.push(3) #stk is the receiver, push is the message The last expression evaluated is what is returned by the method so often no explicit return is needed No return type specified Parameters have no type information so you can pass anything to a method, but if you treat it improperly, you’ll get an error Ruby Notes

Methods, continued Don’t use braces Method starts with def Method ends with end Default parameters can be provided def foo(n1 = 0, n2 = 3) . end Ruby Notes

Methods can return more than one value #!/usr/local/bin/ruby def increment(n) return n, n + 1; end n = 3; n, ninc = increment(n); puts "#{n} incremented is #{ninc}"; http://www.cs.appstate.edu/~can/classes/3490/Ruby/return.rb Ruby Notes

Methods, continued Methods can also be passed a block in addition to other parameters Blocks are called from the method with a yield statement Parameters can be sent to the block http://www.cs.appstate.edu/~can/classes/3490/Ruby/block.rb You can pass multiple parameters to a method by prefixing formal parameter with a * def foo(*a) #all arguments passed to foo are #bundled into an array http://www.cs.appstate.edu/~can/classes/3490/Ruby/params.rb Ruby Notes

Methods, continued Methods can be private, protected or public public – can be called from anywhere in the code; by default, class methods are public protected – can be called only within the class in which the method is defined or within derived classes private – can be called only within the class in which the method is defined methods are defined to be public, protected or private by inserting public, protected or private key word Ruby Notes

Methods, continued class Aclass public #methods below here, up to private, are public def initialize() . end def foo() private #goo is private def goo() Ruby Notes

Instance Methods Act upon instances of the class def instanceMethod(…) end Ruby Notes

Class Methods Method that is not tied to an instance of the class in which they are declared In Java/C++, we create these by declaring them to be static In Ruby, they are created by prefixing the method name with the class name and a period def Classname.methodname(…) Ruby Notes

Instance variables Instance variables start with an @ sign, don’t need to be declared and are protected The visible (readable and/or writable) instance variables are called an object’s attributes attr_reader – shortcut for creating a methods for reading attributes attr_writer – shortcut for creating methods for writing to attributes attr_accessor – shortcut for creating two methods – one for reading and one for writing to an attribute Ruby Notes

#!/usr/local/bin/ruby class Class attr_reader :teacher, :name; def initialize(teacher, name, size) @teacher = teacher @name = name @size = size end cs3490 = Class.new("Cindy Norris", "CS 3490", 21) puts cs3490.name puts cs3490.teacher #no accessor method for size, so can't: puts cs3490.size #can't modify cs3490.name, cs3490.size, cs3490.size http://www.cs.appstate.edu/~can/classes/3490/Ruby/class.rb Ruby Notes

Virtual Attributes Putting an = at the end of a method allows the method to be used as a target of an assignment class Time def minutes=(newmin) @hours = newmin / 60.0 end t = Time.new() t.minutes = 453 To the user of the class, it looks like minutes is a writeable attribute Ruby Notes

Class Variables Shared among all objects of a class Start with @@ Initialized with an assignment statement within the body of the class definition (outside of a method definition) Ruby Notes

class CSClasses @@deptCount = 0; def initialize() @classes = Array.new() end def addClass(teacher, name, size) aClass = OneClass.new(teacher, name, size) @classes.insert(0, aClass); @@deptCount += 1; def teacherCount(t) count = 0; @classes.each do |c| if c.teacher == t count += 1 return count def CSClasses.deptCount @@deptCount #!/usr/local/bin/ruby class OneClass def initialize(t, n, s) @teacher = t @name = s @size = n end attr_reader :teacher, :name, :size; http://www.cs.appstate.edu/~can/classes/3490/Ruby/CSClasses.rb

Inheritance Specified by: class SubClassName < SuperClassName super can be used to call a super class method of the same name Super without parens causes the same parameters to be passed to the parent method as were received by the child method Default parent of every class is the Object class - Object class contains 35 instance methods Ruby Notes

Inheritance, continued Name of the constructor is called initialize Construction of an object will cause an initialize function to be searched for starting with the class of the object just created and then search upward through the ancestors only one constructor will be executed unless the constructor includes a call to super Ruby Notes

#!/usr/local/bin/ruby class GrandParent def initialize puts "GrandParent Constructor" end class Parent1 < GrandParent def initialize() puts "Parent1 Constructor"; class Parent2 < GrandParent super(); puts "Parent2 Constructor"; class Child1 < Parent1 puts "Child1 Constructor"; class Child2a < Parent2 def initialize() super(); puts "Child2 Constructor"; end class Child2b < Parent2 child1 = Child1.new; puts "\n"; child2a = Child2a.new; child2b = Child2b.new; What is the output? http://www.cs.appstate.edu/~can/classes/3490/Ruby/constructors.rb

type + " with attributes " + attributes + " is " + @area.to_s; class Polygon def initialize @area = 0 end def printArea puts "The area of " + type + " with attributes " + attributes + " is " + @area.to_s; class Rectangle < Polygon def initialize(height, width) super(); @height = height; @width = width; end def type "rectangle" def attributes "height = " + @height.to_s + " width = " + @width.to_s def calcArea() @area = @height * @width; Ruby Notes

Inheritance, continued Supports only single inheritance but a class can include the functionality of any number of mixins A mixin is a module that has been included by a class Ruby Notes

What is a module? Similar to a Java abstract class in that it can’t be instantiated Can contain instance methods, class methods, class variables, instance variables and constants Ruby Notes

How are modules used? Module constants can be accessed by prefixing constant by name of module and :: ModuleName::CONSTANT Module class methods can be called by prefixing method name by the class name and a dot ModuleName.methodname(..) Or, modules can be included by a class Everything in the module becomes a member of the class Ruby Notes

#!/usr/local/bin/ruby #This example shows how to define and use a module #Since this only has constants and class methods, it doesn't #need to be a "mixin" module Math #you can access MYpi as Math::Mypi MYpi = 3.141592654 #but to show you how to call module methods, I include #this class method (notice class methods are prefixed by #classname and a dot) def Math.getPI() return MYpi end Ruby Notes

class Circle attr_reader :radius def initialize(r) @radius = r end def areaUsingConstant() #prefix constants in the module with the name of the module #and :: Math::MYpi * @radius * @radius def areaUsingClassMethod() #call the ClassMethod in Math Module Math.getPI()* @radius * @radius c = Circle.new(2.3) puts "Area of circle with radius #{c.radius} = #{c.areaUsingConstant}" puts "Area of circle with radius #{c.radius} = #{c.areaUsingClassMethod}" http://www.cs.appstate.edu/~can/classes/3490/Ruby/circle.rb

Here's same example, but Math is used as a mixin #!/usr/local/bin/ruby module Math MYpi = 3.141592654 end class Circle include Math attr_reader :radius def initialize(r) @radius = r def area() MYpi * @radius * @radius c = Circle.new(2.3) puts "Area of circle with radius #{c.radius} = #{c.area}" Ruby Notes

Polymorphism Ruby types call a “method call” sending a message to a receiver Messages to method bodies are dynamically bound If an appropriate method can not be found in the chain of inheritance, an error (Object#method_missing) occurs Ruby Notes

class Professor < Person def initialize(name) name = "Professor " + name; super(name) end def grade(student) student.grade('A') prof = Professor.new('Cindy Norris'); stud = Student.new('Jill Guy'); prof.grade(stud); puts prof.name + " assigned " + stud.name + " the grade " + stud.thegrade; #!/usr/local/bin/ruby class Person def initialize(name) @name = name; end attr_reader :name; class Student < Person name = "Student " + name; super(name) def grade(thegrade) @thegrade = thegrade attr_reader :thegrade http://www.cs.appstate.edu/~can/classes/3490/Ruby/person.rb

More examples List parent class with stack and queue subclasses http://www.cs.appstate.edu/~can/classes/3490/Ruby/list.rb Similar example, but the list is a module (can't create an instance of it) and is used as a mixin (it becomes part of the classes that use it) http://www.cs.appstate.edu/~can/classes/3490/Ruby/listMixin.rb

Type System Ruby uses duck typing type of the variable is determined by what it can do Duck typing is dynamic – type is determined at run time and can change during run time Ruby Notes

Is there more to Ruby? Yes, loads! Exception handling Threads and processes Unit testing Namespaces Ruby debugger RDoc for creating ruby documentation Using Ruby for web applications (Rails) Graphics Using Ruby in conjunction with other languages (C, TK, Perl) Ruby reflection Ruby Notes