The Object class is the base for Java Language and we all reading the below sentences from day one of our Java Programming.
Every class is a Child of the Object class.
Every class is a Child of the Object class.
Every class in Java extends Object class.
Object class is the super class of every Java Class.
We all read the above lines and stop there. Only few have a return question about the reason behind making the Object class as a super class. There is no secret reason or any magic behind making Object as a super class. Keeping it simple and short, the reason is Inheritance. Yes. The same key feature of OOP, inheritance theory applies here too. To reduce the code duplication.
If you observe the methods in Object class, those the basic methods that every class should contain and they are very basic features or functionalities that every class should have and support (like getting Class name, String representation of Object etc. ).
Object class provides the basic functionality methods which are already implemented in it. You need not to provide(optional) implementation for those methods unless you have a specific requirement. In such cases, you need to override those methods in your Class. Otherwise the default implementation in Object class executes.
Let's divide the methods of Object class by features and you'll realize why those methods put in Object Class.
For string representation of Class :
toString();
For copy of an object :
clone();
For checking equality of an object :
equals();
To support hash techniques on object :
hashCode();
To support garbage collection :
finalize();
To give the Class name of object :
getClass();
To support syncronization on object :
public final void notify()
public final void notifyAll()
public final void wait()
public final void wait()
public final void wait()
If you see, all the methods mentioned is a part of basic feature for every class and Java designers already implemented for you. Otherwise every developer is to keep writing these implementation on their own and end of the day, there will be no business logic written (of course bugs are obvious). Otherwise each person implements in their own style and there will be no uniqueness even. So designers separated these basic functions and made a Class and extended inbuilt.
Other than that big gotcha, there are other uses as well in designer minds. For example to make generic functions with Object as a parameters to methods, to provide default implementations as well, since every Class in Java Is-A Object.
Look at a function which we can write the functionality without even knowing the actual Object being passed to it. For the method writeObject() ,you can pass any instance to it, since it accept all types of Objects. Any ways with Java 1.5 we have generics included for the same purpose..
public final void writeObject(Object obj)These are my observations and comment if you have a reason. Will include in the post.
No comments:
Post a Comment