Lucyna Min
Lucyna Min

Reputation: 15

Object Class (polymorphism, casting)

I'm a newbie learning Java and I just read about Object class as a superclass of all objects. I wonder now, if I want to create more classes (according to polymorphism rules) and the Object class is supposed to be "on top", can I create it or should I just treat it as "default"?

Upvotes: 0

Views: 40

Answers (1)

Benjamin M
Benjamin M

Reputation: 24527

The Object class in Java is the root of all classes.

Every class you create implicitly extends Object. Though those class definitions are equal:

class MyClass { }
class MyClass extends Object { }

The extends Object part is done for you automatically by the compiler.

If you have a class hierarchy, then the first class in this hierarchy is always (implicitly) Object:

class A { } // A will implicitly extend Object
class B extends A { } // though B is of type Object, too, because A is, too

That's the reason why you can cast everything (except for primitives) to Object:

A a = new A(); // works
B b = new B(); // works

Object a = new A(); // works, because A implicitly extends Object
Object b = new B(); // works, because B extends A, and A extends Object, and though B extends Object, too

A a = new B(); // works, because B extends A
B b = new A(); // fails, because A does not extend B

In general you never write extends Object yourself, because it is done for you automatically by Java.

Upvotes: 1

Related Questions