Sunday, November 26, 2006

Class Inheritance example in Ruby

Following is an example of class inheritance in ruby programming. Do make notice of use of super and "<" for inheritance.
 
class HelloParent
    attr_accessor :name
    def initialize( name )
        print "\nThis is a parent program, Hello #{name}"
        @name = name
    end
    def sayHello
        print "\nI am asked to say Hello
#{@name}"
    end
       
end
class HelloChild < HelloParent
    def initialize( name, surname )
        print "\nI am a child class #{surname}"
        super(name)
    end
end

child = HelloChild.new( "Ak", "Kumar" )
child.sayHello
 
In avove try putting something like following:
 
child = HelloChild( "Ak", "Kumar" )
child = new HelloChild( "Ak", "Kumar" )
 
 
And you get the following error:
 
hw2.rb:21: undefined method `HelloChild' for main:Object (NoMethodError)

0 Comments:

Post a Comment

<< Home