Inheritance example in JRuby

In the previous sections of JRuby tutorials you became familiar with the way that how Classes are to be declared in JRuby and how these can be used to call methods of a class.

Inheritance example in JRuby

Inheritance example in JRuby

     

In the previous sections of JRuby tutorials you became familiar with the way that how Classes are to be declared in JRuby and how these can be used to call methods of a class. Now you will learn that how to implement Inheritance in JRuby. 

In this example we are defining one class named as "Base" and another class "Derive" which inherits the Base class. It is same as we define a class in Java and inherit that by extending that class. We use "<" symbol to show inheritance in JRuby.

 

 

 

 

class Base
   def add
   puts "Hello Base"
   end
  end

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

 

In above lines of code we have defined a class Base and one method add in it. Another defined class is Derive which inherits Base as "Derive < Base". Now we have created a new instance of Derive class with the "new" as "derive = Derive.new"
"
derive.add"  - will call Base class "add" method and "derive.addDerive" - will call Derive class addDerive method.

Here is the example code of InheritJRuby.rb as follows:

InheritJRuby.rb

# Example program of Inheritance in JRuby

  class Base
   def add
   puts "Hello Base"
   end
  end

  class Derive < Base
  def addDerive
  puts "Hello Derived"
  end
   end
   # Creating instance of Derive class
  derive = Derive.new
  puts derive.add
  puts derive.addDerive


Output:
 

Output of this program is as follows:

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


Download Code