O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.7. The Universal Superclass

I must now reveal something I have been keeping from you. All the classes that you define are subclasses by default—whether you like it or not. All your classes have a standard class, Object, as a base, so Object is a superclass of every class. You never need to specify the class Object as a base in the definition of your classes—it happens automatically.

There are some interesting consequences of having Object as a universal superclass. For one thing, a variable of type Object can store a reference to an object of any class type. This is useful when you want to write a method that needs to handle objects of unknown type. You can define a parameter to the method of type Object, in which case a reference to any type of object can be passed to the method. When necessary you can include code in the method to figure out what kind of object it actually is (you'll see some of the tools that will enable you to do this a little later in this chapter).

Of course, your classes will inherit members from the class Object. These all happen to be methods, of which seven are public, and two are protected. The seven public methods are:

MethodPurpose
toString()This method returns a String object that describes the current object. In the inherited version of the method, this will be the name of the class, followed by '@' and the hexadecimal representation for the object. This method is called automatically when you concatenate objects with String variables using +. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required