Reputation: 2237
What is the function of the class Object
in java? All the "objects" of any user defined class have the same function as the aforementioned class .So why did the creators of java create this class?
In which situations should one use the class 'Object'?
Upvotes: 0
Views: 107
Reputation: 3769
What Java implements is sometimes called a "cosmic hierarchy". It means that all classes in Java share a common root.
This has merit by itself, for use in "generic" containers. Without templates or language supported generics these would be harder to implement.
It also provides some basic behaviour that all classes automatically share, like the toString method.
Having this common super class was back in 1996 seen as a bit of a novelty and cool thing, that helped Java get popular (although there were proponents for this cosmic hierarchy as well).
Upvotes: 1
Reputation: 12206
Object
provides an interface with functionality that the Java language designers felt all Java objects should provide. You can use Object
when you don't know the subtype of a class, and just want to treat it in a generic manner. This was especially important before the Java language had generics support.
There's an interesting post on programmers.stackexchange.com about why this choice was made for .NET, and those decisions most likely hold relevance for the Java language.
Upvotes: 1
Reputation: 77177
Pretty much the only time that Object
is used raw is when it's used as a lock object (as in Object foo = new Object(); synchronized(foo){...}
. The ability to use an object as the subject of a synchronized
block is built in to Object
, and there's no point to using anything more heavyweight there.
Upvotes: 2
Reputation: 2104
Since all classes in Java are obligated to derive (directly or indirectly) from Object
, it allows for a default implementation for a number of behaviours that are needed or useful for all objects (e.g. conversion to a string, or a hash generation function).
Furthermore, having all objects in the system with a common lineage allows one to work with objects in a general sense. This is very useful for developing all sorts of general applications and utilities. For example, you can build a general purpose cache utility that works with any possible object, without requiring users to implement a special interface.
Upvotes: 3