Friday, June 30, 2006

Writing our own Class

A class is a combination of state (for example, the quantity and the product id) and methods that use the state.

The Object is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.

Let's write our own class - MotorCycle.rb.
class MotorCycle
def initialize(make, color)
# Instance variables
@make = make
@color = color
end
def startEngine
if (@engineState)
puts 'Engine Running'
else
@engineState = true
puts 'Engine Idle'
end
end
def dispAttr
puts 'Color of MotorCycle is ' + @color
puts 'Make of MotorCycle is ' + @make
end
m = MotorCycle.new('Yamaha', 'red')
m.startEngine
m.dispAttr
m.startEngine
end

Read this very carefully, it's a brain bender! Classes in Ruby are first-class objects - each is an instance of class Class. When a new class is defined (typically using class Name ... end), an object of type Class is created and assigned to a constant (Name. in this case). When Name.new is called to create a new object, the new instance method in Class is run by default, which in turn invokes allocate to allocate memory for the object, before finally calling the new object's initialize method.

A class's instance methods are public by default; anyone can call them. Let's refer to the program ClassAccess.rb below. The private directive is the strictest; private methods can only be called from within the same instance. Protected methods can be called in the same instance and by other instances of the same class and its subclasses.
class ClassAccess
def m1 # this method is public
end
protected
def m2 # this method is protected
end
private
def m3 # this method is private
end
end
Instance variables are not directly accessible outside the class. To make them available, Ruby provides accessor methods that return their values. The program Accessor.rb illustrates the same.
# Accessor.rb
# First without accessor methods
class Song
def initialize(name, artist)
@name = name
@artist = artist
end
def name
@name
end
def artist
@artist
end
end

song = Song.new("Brazil", "Ricky Martin")
puts song.name
puts song.artist

# Now, with accessor methods
class Song
def initialize(name, artist)
@name = name
@artist = artist
end
# the instance variable @name and @artist will
# be automatically created below
attr_reader :name, :artist # create reader only
# For creating reader and writer methods
# attr_accessor :name
# For creating writer methods
# attr_writer :name

end

song = Song.new("Brazil", "Ricky Martin")
puts song.name
puts song.artist
There are many classes and modules (more on this later) built into the standard Ruby language. They are available to every Ruby program automatically; no require is required. Some built-in classes are Array, Bignum, Class, Dir, Exception, File, Fixnum, Float, Integer, IO, Module, Numeric, Object, Range, String, Thread, Time. Some built-in Modules are Comparable, Enumerable, GC, Kernel, Math. The following Class Hierarchy is informative.

Inheritance allows you to create a class that is a refinement or specialization of another class. Refer program Inherit.rb.
class GF
def initialize
puts 'In GF class'
end
def gfmethod
puts 'GF method call'
end
end

# class F sub-class of GF
class F < GF
def initialize
puts 'In F class'
end
end

# class S sub-class of F
class S < F
def initialize
puts 'In S class'
end
son = S.new
son.gfmethod
end

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

11 Comments:

Blogger SatishTalim said...

Next week, I shall start with Rails. In case, there are some Ruby features that we require in Rails; I shall discuss the same at that point in time.

11:54 AM  
Blogger raj said...

This comment has been removed by a blog administrator.

12:12 PM  
Blogger raj said...

My Doubts:
1. def initialize(....) --> is this same as a constructor similar to in C++/Java.
2. Do I nedd to include [ def initialize (....) method ; if I am not passing any agrugments from object.
m = MotorCycle.new() # no argument
3. Do I need to create object always within the [ Class XYZ---- end ]block. Can't I create object outside the class?

12:16 PM  
Blogger Ashish Kulkarni said...

Hi Satish,

A few questions around classes and inheritence.

1. Ruby, just like Java, only supports single inheritence and not multiple inheritence like C++. So does it allow interfaces?

2. Does Ruby allow abstract classes? And abstract methods?

3. Does Ruby allow polymorphism? If so, could you give an example please?

4. Is Ruby code always interpreted? Is there a bytecode or machine code convertor for Ruby?

5. Do we need to import libraries explicitly?

6. Does the name of the file have to match the name of the Class?

7. Can you define anonymous classes? Or internal classes?

8. Does Ruby allow object serialisation?

Sorry, I am just listing all my interview questions here :-).

1:47 PM  
Blogger sharifkazi said...

This comment has been removed by a blog administrator.

2:51 PM  
Blogger sharifkazi said...

Can we write inner classes in Ruby??

2:59 PM  
Blogger Jai Porje said...

Hello,
I just wanted to know that
Can there be more than one constructors?

6:15 PM  
Blogger DeepaliAhirrao said...

Sir,
I observed that we have to define function before the line that make a call to it. Like in MotorCycle.rb, if I place the function dispAttr just before the last end statement of class, then I get error.

6:28 PM  
Blogger raj said...

# Hi Jai..I think we CANNOT use more than one constructor.[Constructors cant be overloaded] I tried the below Pgm. If you uncomment, it doesnt work then.

class MotorCycle
#def initialize()
# puts 'no argument'
# end

def initialize(just_one)
puts 'one argument'
end

puts "Just one constructor"
#puts "With Two constructor"
#obj1=MotorCycle.new();
obj2=MotorCycle.new('one');

end

8:04 PM  
Blogger Ashish Kulkarni said...

Hi Satish,

Great!!! I look forward to getting onto Rails.

Regards,

Ashish.

8:19 PM  
Blogger Eswar Malla said...

I tried an example. No method overloading too ???

8:27 AM  

Post a Comment

Links to this post:

Create a Link

<< Home