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

4 Comments:

Blogger Unknown 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 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 Ashish Kulkarni said...

Hi Satish,

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

Regards,

Ashish.

8:19 PM  
Blogger eswar said...

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

8:27 AM  

Post a Comment

<< Home