The root class in Java
The Java Standard Library has a class named Object
that is the parent of all standard and your classes by default. Any class extends this class implicitly, therefore it's a root of inheritance in Java programs.
The class belongs to the java.lang
package that is imported by default.
Let's create an instance of the Object
.
Object anObject = new Object();
The Object
class can refer an instance of any class because the instance is a kind of Object
as well (upcasting).
Long number = 1_000_000L;
Object obj1 = number; // an instance of Long can be cast to Object
String str = "str";
Object obj2 = str; // as well as an instance of String
When we declare a class, we can extend the Object
class in the explicit form.
Here is an example, do not repeat it:
class A extends Object { }
Methods provided by the Object class
Object
class provides some common methods to all subclasses. It has nine instance methods (excluding overloaded methods) which can be divided into four groups:- threads synchronization: wait, notify, notifyAll;
- object identity: hashCode, equals;
- object management: finalize, clone, getClass;
- human-readable representation: toString;
Of course, this way to group methods does not pretend to be ideal, but it can help you to remember them.
- The first group of methods (wait, notify, notifyAll) are for working in multithreaded applications.
- The method hashCode returns a hash code value for the object.
- The method equals indicates whether some other object is "equal to" this one.
- The method finalize is called by the garbage collector (GC) on an object when GC want to clean up it.
- The method clone creates and returns a copy of the object.
- The method getClass returns an instance of Class, which has information about the runtime class.
- The method toString returns a string representation of the object.
Some of the listed methods are native that means they are implemented in "native" code. It's typically written in C or C++. Native methods are usually used to interface with system calls or libraries written in other programming languages.