If a class has been previously defined how can I tell it to inherit from a class Parent
For instance:
class Parent
..
end
class Klass
..
end
Now I want it to inherit from Parent
I cant re-open the class and set it because I will get a class mismatch error
class Klass < Parent
..
end
Specifically I am trying to find out how to set the class inheritance on a class im creating through Object.const_set
klass = Object.const_set('Klass', Class.new)
How can I tell Klass to inherit from class Parent?
Ruby does not support multiple inheritance. It only supports single-inheritance (i.e. class can have only one parent), but you can use composition to build more complex classes using Modules.
Inheritance concept is to inherit properties from one class to another but not vice versa. But since parent class reference variable points to sub class objects. So it is possible to access child class properties by parent class object if only the down casting is allowed or possible....
Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class.
Inheritance between classes. Classes in C++ can be extended, creating new classes which retain characteristics of the base class. This process, known as inheritance, involves a base class and a derived class: The derived class inherits the members of the base class, on top of which it can add its own members.
There is no way to change the superclass of an already existing class.
To specifiy the superclass of a class you're creating dynamically, you simply pass the superclass as an argument to Class.new
.
class Parent
end
klass = Class.new(Parent)
klass.superclass #=> Parent
Just as a side note: You're not creating the class with const_set
. You're creating it with Class.new
. You're simply storing the created class in a constant with const_set
. Once const_set
is invoked, Class.new
has already happened and the superclass cannot be changed anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With