Ruby Objects, Classes and Variables CS 480/680 – Comparative Languages.

Slides:



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

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Python Objects and Classes
Object-Oriented Programming
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Web Application Development Slides Credit Umair Javed LUMS.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
And other languages….  Get out a piece of paper  You’ll be tracing some code (quick exercises) as we go along.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
© The McGraw-Hill Companies, 2006 Chapter 8 Extending classes with inheritance.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
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,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
CS 106 Introduction to Computer Science I 11 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
ASP.NET Programming with C# and SQL Server First Edition
Inheritance Review/Recap. ClassA extends ClassB ClassA now inherits (can access and use) all public and protected elements of ClassB We can expect the.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Java Programming Review (Part I) Enterprise Systems Programming.
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.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CMSC 330: Organization of Programming Languages Ruby Hash Tables (and other topics)
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Ruby and the tools Topics Ruby Rails January 15, 2014 CSCE 740 Software Engineering.
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers Blocks Iterators Spring 2014 CSCE 740 Software Engineering.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
Inheritance Chapter 10 Programs built from objects/instances of classes An O.O. approach – build on earlier work. Use classes in library and ones you have.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Programming in Java CSCI-2220 Object Oriented Programming.
+ Ruby and other programming Languages Ronald L. Ramos.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Learning Ruby Classes. Variables Variables in Ruby can contain data of any type. You can use variables in your Ruby programs without any declarations.
Introduction to information systems RUBY dr inż. Tomasz Pieciukiewicz.
Ruby Duck Typing, Classes & Inheritance CSE 413 Autumn 2008.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Ruby Inheritance and other languages….
Topic: Classes and Objects
Variables All variables hold object references
Java Primer 1: Types, Classes and Operators
12 Data abstraction Packages and encapsulation
Classes, Objects, And Variables
Web Systems Development (CSC-215)
Object Oriented Programming (OOP) LAB # 8
Ruby and the tools 740Tools05ClassesObjectsVars
Ruby Classes.
CSCE 740 Software Engineering
Java Programming Language
Presentation transcript:

Ruby Objects, Classes and Variables CS 480/680 – Comparative Languages

Ruby Classes2  Remember, in Ruby variables are created automatically the first time they are accessed  Thus, there is no variable declaration section in a Ruby class, variables are created in the initialize method (the equivalent of a C++ constructor) class Song def initialize(name, artist, = = = duration end

Ruby Classes3 Using the Class aSong = Song.new("Bicylops", "Fleck", 260) @duration=260>" aSong.to_s »"# "  How can we call to_s and inspect, when we have not defined them for this class?  Answer: All classes are subclasses of class Object to_s and inspect are inherited from Object

Ruby Classes4 Overriding the Superclass  Classes can be reopened any time Which means that you can override or extend built- in classes just by opening them  Notice the missing return() in to_s class Song def to_s "Song: end End aSong = Song.new("Bicylops", "Fleck", 260) aSong.to_s »"Song: Bicylops--Fleck (260)"

Ruby Classes5 Inheritance  “< Song” – indicates that KaraokeSong is a subclass of Song. All methods of Song are included in KaraokeSong Data members are not explicitly included, but the are created by the call to super in initialize class KaraokeSong < Song def initialize(name, artist, duration, lyrics) super(name, artist, = lyrics end

Ruby Classes6 Calling the Superclass  Calling super with no arguments calls the same- named method in the superclass with the same arguments class KaraokeSong < Song # Format ourselves as a string by appending # our lyrics to our parent's #to_s value. def to_s super + " end aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now...") aSong.to_s » "Song: My Way--Sinatra (225) [And now...]"

Ruby Classes7 Accessing Data Members class Song attr_reader :name, :artist, :duration end Is the same as this: class Song def end def end def end

Ruby Classes8 Writing Data Members class Song attr_writer :duration end Is the same as this: class Song def duration=(newDuration) # Methods = newDuration # in “=“ are end # special end aSong = Song.new("Bicylops", "Fleck", 260) aSong.duration » 260 aSong.duration = 257 aSong.duration » 257

Ruby Classes9 Class state is protected  In Ruby, you can only access data members (“state”) of a class through class methods class Myclass def = = 1 end attr_reader(:state1, :state2) end myobj = Myclass.new puts myobj.state1, myobj.state2 myobj.state1 = 7 objectstate.rb:13: undefined method `state1=' for # (NoMethodError)

Ruby Classes10 Virtual Data Members  When using access methods, data can be converted before reporting, so data members can be accessed in multiple ways: class Song def # force floating point end def = (value*60).to_i end aSong = Song.new("Bicylops", "Fleck", 260) aSong.durationInMinutes » aSong.durationInMinutes = 4.2 aSong.duration » 252

Ruby Classes11 Class Variables  Class variables store data stored among all instances of a class There is only one class variable storage location for the entire class Must be initialized before use in the class definition  Class variables start with

Ruby Classes12 Class Variables class Song = 0 # Play count for ALL songs def initialize(name, artist, = = = = 0 # Play count for THIS song end def += 1 += 1 "This song: plays. Total plays." end

Ruby Classes13 Class Methods  Some methods need to be run without being attached to any particular instance  Example: Test if a file is readable Can’t open the file if it is not readable File.readable?(“Filename”) might be defined to allow this test without any particular file variable  Defined as Classname.methodName class Example def instMeth # instance method end def Example.classMeth # class method end

Ruby Classes14 Class Constants  Recall that constants begin with uppercase letters  Constants defined outside of any class are global, while those defined within a class are local: class SongList MaxTime = 5*60 # 5 minutes def SongList.isTooLong(aSong) return aSong.duration > MaxTime end

Ruby Classes15 Variables in Ruby  Variables in Ruby hold references to objects! A reference is basically an address with some class/type information  This can make assignment somewhat tricky!  See variables.rb

Ruby Classes16 Singletons  Suppose you want only one object of a particular class, and every time a new instance is “created” it refers to the same object? This is a design pattern called a singleton class Logger private_class_method :new = nil def Logger.create = new unless end Logger.create.id » Makes the new() method private Use Logger.create() instead.

Ruby Classes17 Alternative constructors  New calls initialize() with the same parameters passed to itself.  You can call new from other methods: class Shape def initialize(numSides, perimeter) #... end class Shape def Shape.triangle(sideLength) Shape.new(3, sideLength*3) end def Shape.square(sideLength) Shape.new(4, sideLength*4) end

Ruby Classes18 Access Control  Access control to methods is C++-like class MyClass def method1 # default is 'public' #... end protected # subsequent methods will be 'protected' def method2 # will be 'protected' #... end private # subsequent methods will be 'private' def method3 # will be 'private' #... end public # subsequent methods will be 'public' def method4 # and this will be 'public' #... end

Ruby Classes19 Alternate notation for access control  Alternately, you can do it this way: class MyClass def method1 end #... and so on public :method1, :method4 protected :method2 private :method3 end This is the notation for a Ruby symbol. We’ll discuss symbols in more detail later…

Ruby Classes20 Method Access  Public – available to anyone  Private – only available to other methods of this class called on the same object  Protected – available only to other methods of this class for this and other objects class Account attr_reader :balance protected :balance def greaterBalanceThan(other) > other.balance end balance() is available to any Account object

Ruby Classes21 Exercises  Create a Ruby class for Students Name, SSN, midterm, final, array of lab scores, array of hw scores Constructor, attr_readers and attr_writers Virtual attributes exam_avg, lab_avg (read-only) Class variable: student_count  Read 5 or 10 student records from a file into an array of student objects, then print them