Is an instance of a class really an instance of its superclass too?

K

Kedar Mhaswade

I understand that the answer to that question is yes.

But then a singleton class (using require 'singleton') can have two or
more instances in a Ruby program, like:

require 'singleton'

class Super
include Singleton
end
class Sub < Super
end

puts Super.instance
puts Sub.instance

#=> <Super:0x000000024b5648>
#=> <Sub:0x000000024b55d0>

Doesn't this mean we have two instances of a class (Super) whose only
one instance should have been in the program (because the class included
'singleton')? IOW, shouldn't class Sub < Super be disallowed?

Thanks,
Kedar
 
G

Gary Wright

Doesn't this mean we have two instances of a class (Super) whose only
one instance should have been in the program (because the class = included
'singleton')? IOW, shouldn't class Sub < Super be disallowed?

I think you answer your own question. The contract created by the =
'singleton' feature is in regards to direct instances and not indirect =
instances via a subclass.

Making the contract more restrictive as you suggest, would limit the use =
cases for no particular reason. If you don't want a subclass, then don't =
create one. In general I think it is better to avoid arbitrary =
restrictions. In most cases, with Ruby, those restrictions don't really =
prevent anything because methods and classes can always be redefined.


Gary Wright=
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top