Method Overriding in JRuby

In this part of JRuby tutorial you will know to implement overriding of methods between the classes.

Method Overriding in JRuby

Method Overriding in JRuby

     

In this part of JRuby tutorial you will know to implement overriding of methods between the classes. In earlier examples of JRuby you have studied a lot about to create class, inheriting class and calling methods of classes. Now in this example we will introduce you with the case of overriding of methods in JRuby program.

In this example we have created a class "Base" and it consists of one method "addBase" and after that we have created another class Derive which consists of one new method addDerive  and one overridden method addBase which have some other functionality rather than Base class by inheriting the Base class.

After creating instances of Base and Derive class when we will call the overridden then it will show you the case of overriding that Base class method is overridden.Here is the example code of OverrideJRuby.rb as follows:

 

 

 OverrideJRuby.rb

# Example program of Inheritance in JRuby

class Base
  def addBase
   puts "Hello Base"
   end
end

class Derive < Base
  def addBase 
   puts "Hello Derived Base"
   end

   def addDerive
  puts "Hello Derived"
   end
end
# Creating instance of Base class
  base = Base.new
  puts base.addBase

# Creating instance of Derive class
   derive = Derive.new
   puts derive.addBase
   puts derive.addDerive

 Output:

C:\JRuby>jruby OverrideJRuby.rb
Hello Base
nil
Hello Derived Base
nil
Hello Derived
nil

Download Source Code