Why Object is Super Class in Java?
java.lang.Object class is the super base class of all Java classes. Every other Java classes descends from Object. Should we say the God class? Why is that so? This Java article is to discuss around it.
In Mathematics, an axiom is a starting point of reasoning using which other statement can be logically derived. The concept of Object class as super class of all classes in Java looks similar to it.
It is not a explicit requirement forced on the developer. If a class is declared without extending another class then it will implicitly extend Object class. This is taken care of by the JVM. This is not applicable for the interfaces. A Java interface does not extends the Object.
Following could be the reasons for this design decision,
- By having the Object as the super class of all Java classes, without knowing the type we can pass around objects using the Object declaration.
- Before generics was introduced, imagine the state of heterogeneous Java collections. A collection class like ArrayList allows to store any type of classes. It was made possible only by Object class hierarchy.
- The other reason would be to bring a common blueprint for all classes and have some list of functions same among them. I am referring to methods likehashCode(), clone(), toString() and methods for threading which is defined in Object class.
This concept cannot be generalized to all object oriented programming (OOPS) languages. For instance, in C++ there is no such super class of all classes.
Super class of String, Object, Class
Following program shows
- the super class of String class.
- the super class of Object class
- the super class of Class class
package com.javapapers.java; public class SuperClass { public static void main(String... args) { String str = new String("Hi"); Class strClass = str.getClass(); System.out .println("Super class of String: " + strClass.getSuperclass()); Object obj = new Object(); Class objClass = obj.getClass(); System.out .println("Super class of Object: " + objClass.getSuperclass()); Class classClass = objClass.getClass(); System.out.println("Super class of Class: " + classClass.getSuperclass()); } }
Output
Super class of String: class java.lang.Object Super class of Object: null Super class of Class: class java.lang.Object
No comments:
Post a Comment