Types in Ruby and other languages….  Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
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.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Written by: Dr. JJ Shepherd
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
ISBN Chapter 7 Expressions and Assignment Statements.
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Compunet Corporation1 Programming with Visual Basic.NET Creating and Using Classes Lecture # 8 Tariq Ibn Aziz.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
C++ fundamentals.
Expressions, Data Conversion, and Input
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Type Equivalence Rules Ada –Strict name equivalence except for almost everything Unique array constructors give rise to unique types Subtypes can create.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
Java 2 More Java Then Starbucks ;-). Important Terms Primitive Data – Basic, built-in values (characters & numbers) Data Type – Used to talk about values.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Chapter 9 Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design.
Also “open class” and other languages….  A module is a named group of methods, constants, and class variables  All classes are modules  Modules are.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Object-Oriented Design Justin Callanan CS 597. Object-Oriented Basics ● Data is stored and processed in “objects” ● Objects represent generalized real.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
Object-Oriented Programming Chapter Chapter
Object Oriented Programming
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSI 3125, Preliminaries, page 1 Data Type, Variables.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Written by: Dr. JJ Shepherd
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
What do you need to know about a new language?
Object-Oriented Concepts
OOP: Encapsulation &Abstraction
Chapter 7: Expressions and Assignment Statements
types in Ruby and other languages…
CSC 205 Java Programming II
Chapter 7: Expressions and Assignment Statements
Data Conversion & Scanner Class
C Basics.
Type Conversion, Constants, and the String Object
Polymorphism and access control
Outline Anatomy of a Class Encapsulation Anatomy of a Method
CIS 199 Final Review.
Java Programming Language
Presentation transcript:

types in Ruby and other languages…

 Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison  Object type type-safety type conversions  Class methods  Class variables  Inheritance – another lecture

 Widening Conversions: can include at least approximations to all of the values of the original type. Examples (Java/C++) byte to short, int, long, float or double short to int, long, float or double char to int, long, float or double int to long, float or double long to float or double float to double  Narrowing conversions: cannot include all of the values of the original type short to byte or char char to byte or short int to byte, short, or char long to byte, short, char or int float to byte, short, char, int or long double to byte, short, char, int, long or float

 Even widening conversions may lose accuracy. Example: integers stored in 32 bits, 9 digits of precision. Floating point values also stored in 32 bits, only about 7 digits of precision (because of space used for exponent). Conversions should be used with care! Warnings should not just be ignored… Strongly typed language minimizes type conversions

 Every value in Ruby is (or behaves like) an object 2.times { puts “hey”}  Objects are instances of classes  BasicObject is superclass  Objects are strictly encapsulated What does that mean? Not covered: frozen or tainted objects

 Protect instance variables from outside forces (i.e., other classes)  Ruby is strictly encapsulated – you must include setters/getter  Java provides encapsulation – but is it strictly encapsulated? (hint: what is the purpose of access modifiers)

 Every class inherits method new calls allocate to get space (can’t override) calls initialize to create instance variables  Often convenient to provide default parameters for initialize def initialize(x, @z = x,y,z end

class Cat def = name, age end def to_s end def end def end def end def end c = Cat.new("Fluffy", 2) puts c puts c.name c.age=5 puts c.age puts c.to_s new calls initialize to_s like toString getters and setters, called attributes last expression in function is indicates instance variable always refer to self DO NOT declare outside of method

class Bottle attr_accessor :ounces attr_reader :label def initialize(label, = = ounces end def end def += other.ounces other.ounces = 0 end def split(scalar) newOunces / -= newOunces newOunces) end def + amount) end def to_s # with an accessor, don't - why? "(#{label}, #{ounces})" end b = Bottle.new("Tab", 16) puts b.label b.ounces = 20 puts "b is #{b}“ puts "result of b2 = b.split 4" b2 = b.split 4 puts "b is #{b}" puts "b2 is #{b2}“ puts "result of b3 = b.add(b2)" b3 = b.add(b2) puts "b3 is #{b3}“ puts "result of b.add!(b2)" b.add!(b2) puts "b is #{b}" puts "b2 is #{b2}“ puts "result of b4 = b3 + 10" b4 = b puts "b4 is #{b4}" attr is example of metaprogramming

 From wikipedia:  Polymorphism (from the Greek many forms) is the provision of a single interface to entities of different types

 If a function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad hoc polymorphism. Ad hoc polymorphism is supported in many languages using function overloading.  If the code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism. In the object-oriented programming community, this is often known as generics or generic programming. See also:

class Can attr_accessor :ounces def initialize(label, = = ounces end def to_s end b = Bottle.new("Tab", 16) c = Can.new(“Coke", 12) b2 = b.add(c) puts "result of b2 = b.add(c)" puts "b2 is #{b2}“ cat = Cat.new b3 = b.add(cat)  If it walks like a duck and quacks like a duck, it must be a duck  any object with needed method will work  undefined method ‘ounces’ for

 x=1  x.instance_of? Fixnum => true  x.instance_of? Numeric => false (even though subclass)  x.is_a? Fixnum => true  x.is_a? Numeric => true  x.is_a? Comparable => true  x.is_a? Object => true  x.class == Fixnum => true  x.class == Numeric => false Quick Ex: how does Java handle?

 Class of an object doesn’t change  Type is more fluid… includes set of behaviors (methods it responds to) i.e, Class != Type….whoaaa  respond_to?

 equal? checks addresses (like == in Java)  for Object, == is synonym for equal?  Most classes override == (like equal in Java)

class Bottle attr_accessor :ounces attr_reader :label def initialize(label, = = ounces end def ==(other) return false if ! other.instance_of? Bottle == other.ounces == other.label end alias eql? == end # Can also has ounces class Can attr_accessor :ounces def initialize(label, = = ounces end b = Bottle.new("Tab", 16) b2 = Bottle.new("Tab", 16) b3 = Bottle.new("Tab", 12) b4 = Bottle.new("Coke", 16) puts "b.equal?(b2) #{b.equal?(b2)}" puts "b == b2 #{b == b2}" puts "b == b3 #{b == b3}" puts "b == b4 #{b == b4}“ puts "b.eql?(b2) #{b.eql?(b2)}" puts "b.eql?(b3) #{b.eql?(b3)}" c = Can.new("Tab", 16) puts "b == c #{b == c}"

 Numeric classes will do type conversions when used with==  eql? is like ==, but no type conversion 1.eql? 1.0  can alias eql? with ==  === used with case statement (1..10) === 5 # true, 5 is in range /\d+/ === “123” # true, matches regex String === “s” # true if s is instance of String Other language with eql?/=== feature?

class Bottle attr_accessor :ounces attr_reader :label def initialize(label, = = ounces end def add(other) raise TypeError, "Bottle argument expected " unless other.is_a? end def add2(other) raise TypeError, "Bottle argument expected " unless other.respond_to? end def rescue raise TypeError, "Cannot add with an argument that doesn't have ounces" end def to_s end class Can attr_accessor :ounces def initialize(label, = = ounces end def to_s end class Cat end b = Bottle.new("Tab", 16) c = Can.new("Coke", 12) puts "result of b2 = b.add(c)" b2 = b.add(c) puts "result of b2 = b.add2(c)" b2 = b.add2(c) puts "b2 is #{b2}" puts "result of b2 = b.add3(c)" b2 = b.add3(c) puts "b2 is #{b2}" cat = Cat.new puts "result of b2 = b.add3(cat)" b2 = b.add3(cat)

class Bottle attr_accessor :ounces attr_reader :label def initialize(label, = = ounces end def each end def [](index) case index when 0, -2 when 1, -1 when :label, "label" when :ounces, "ounces" end b = Bottle.new("Tab", 16) puts "using each" b.each {|x| puts x } puts "[ix]" puts b[0] puts b[-2] puts b[1] puts b[-1] puts "[field name]" puts b["label"] puts b[:label] puts b["ounces"] puts b[:ounces]

 Implement operator (spaceship)  Like compareTo (-1, 0, 1 and nil if not comparable)  Typically include Comparable module as a mixin  Provides =, >(defined in terms of )  Sometimes write == anyway (e.g., one may be case-sensitive, may be more efficient). Best to be consistent.

class Bottle include Comparable attr_accessor :ounces attr_reader :label def initialize(label, = = ounces end def hash #based on Effective Java by Bloch code = 17 code = 37 * code code = 37 * code code end def (other) return nil unless other.instance_of? other.ounces end b = Bottle.new("Tab", 16) b2 = Bottle.new("Tab", 12) b3 = Bottle.new("Coke", 16) b4 = Bottle.new("Tab", 16) puts "b == b2 #{b == b2}" puts "b < b2 #{b < b2}" puts "b > b2 #{b > b2}" puts "b == b3 #{b == b3}" puts "b == b4 #{b == b4}"

class Bottle include Comparable attr_accessor :ounces attr_reader :label MAX_OUNCES = 64 = 0 def initialize(label, = label += 1 if ounces > = MAX_OUNCES = ounces end def Bottle.sum(bottles) total = 0 bottles.each {|b| total += b.ounces } total end def to_s end def self.report #class method puts "Number of bottles created: end bottles = Array.new bottles[0] = Bottle.new("Tab", 16) bottles[1] = Bottle.new("Tab", 16) bottles[2] = Bottle.new("Coke", 16) bottles[3] = Bottle.new("Tab", 20) puts "Total ounces: #{Bottle.sum bottles}" b = Bottle.new("Sprite", 72) puts b Bottle.report Not covered: Class Instance Variables

 Language Concepts Classes Instance variables Object creation Determine object type Object equality Object comparisons Type conversions Type safety Class methods – next lecture Class variables  Ruby new to_s duck typing

Not covered, but may be useful  dup  clone  initialize_copy  marshalling (create from serialized data)