Main Content

What is a universal superclass? Java / Perl / Python / Other OO languages

Archive - Originally posted on "The Horse's Mouth" - 2010-11-13 08:47:14 - Graham Ellis

In any object oriented language, all objects will ultimately inherit from a base class supplied with the language, whether it's explicitly stated or not. That's because every class that you write will need that basic facilities to set up members (objects), and it's also useful to provide you with a handful of standard methods that will work for each and every object - either in their default form, or overridden if you want your class to do something a bit differently.

In Java, everything inherits from the base class Object - directly if you define your class without an extends clause, or indirectly through the heirarcy that you mayhave chosen to set up. Methods provided include finalize (a default destructor), getClass to find out about the type of an object [use with care!], toString which defines how an object is converted to a String, and equal which is used to test whether two objects are considered to be equal. The latter two of these are methods that you'll often want to override in your own classes, and there's a new example on our web site [here].

Perl's UNIVERSAL class includes methods isa to see if an object is of a particular type (literally "is a"), can to test whether a particular method can be run on an object, and DOES to check whether an object can perform a paricular role.

In Python (new style classes) you always inherit from an object:

>>> class Snake(object):
...     pass


>>> spit = Snake()

And you'll find that you get a whole wide range of things (other objects - in Python everything is an object) provided to you by the object class:

>>> dir(spit)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']