Ruby program to override the superclass method into sub-class

Ruby Example: Write a program to override the superclass method into sub-class.
Submitted by Nidhi, on January 27, 2022

Problem Solution:

In this program, we will override the method of superclass into sub-class. Then we will access the overridden method using the object of the sub-class.

Program/Source Code:

The source code to override the superclass method into sub-class is given below. The given program is compiled and executed successfully.

# Ruby program to override the superclass method 
# into sub-class.

# Super class
class SuperClass
	def initialize
		puts "SuperClass constructor";
	end

	def SayHello
		puts "Say hello from SuperClass";
	end
end

class SubClass < SuperClass
	
	def initialize
	    puts "SubClass constructor";
	end
	
	def SayHello
		puts "Say hello from SubClass";
	end
end

subObj = SubClass.new;
subObj.SayHello;

Output:

SubClass constructor
Say hello from SubClass

Explanation:

In the above program, we created two classes SuperClass, SubClass. And, we override the SayHello() method into SubClass by inheriting SuperClass into SubClass. After that, we created an object of SubClass, and called SayHello() method of SubClass.

Ruby Constructors/Destructors, Inheritance Programs »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.