Object Class
In this chapter you will learn:
Get to know Object class
Object
is a superclass of all other classes.
Therefore, Object
can refer to an object of any other class.
Also, a variable of type Object
can also refer to any array.
Object defines the following methods, which means that they are available in every object. The following table lists methods from object class.
Return | Method | Purpose |
---|---|---|
Object | clone() | Creates a new object that is the same as the object being cloned. |
boolean | equals(Object object) | Determines whether one object is equal to another. |
void | finalize() | Called before an unused object is recycled. |
Class | getClass() | Obtains the class of an object at run time. |
int | hashCode() | Returns the hash code associated with the invoking object. |
void | notify() | Resumes execution of a thread waiting on the invoking object. |
void | notifyAll() | Resumes execution of all threads waiting on the invoking object. |
String | toString() | Returns a string that describes the object. |
void | wait() | Waits on another thread of execution. |
void | wait(long milliseconds) | Waits on another thread of execution. |
void | wait(long milliseconds, int nanoseconds) | Waits on another thread of execution. |
getClass()
, notify()
, notifyAll()
, and wait()
are final.
The equals()
method compares the contents of two objects.
It returns true
if the objects are equivalent, and false
otherwise.
The toString()
method returns a string that contains a description of the object.
toString()
method is automatically called when an object is
output using println()
.
clone() and the Cloneable Interface
The clone()
method generates a duplicate copy of the object.
Only classes that implement the Cloneable interface can be cloned.
If you try to call clone()
on a class that does not implement
Cloneable
, a CloneNotSupportedException
is
thrown.
clone()
is declared as protected inside Object.
Let's look at an example of each approach.
The following program implements Cloneable
and
defines the method cloneTest()
, which calls
clone()
in Object
:
class TestClone implements Cloneable {
int a;/* jav a2s . com*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
System.out.println("Cloning not allowed.");
return this;
}
}
}
public class Main {
public static void main(String args[]) {
TestClone x1 = new TestClone();
TestClone x2;
x1.a = 10;
// here, clone() is called directly.
x2 = (TestClone) x1.clone();
System.out.println("x1: " + x1.a);
System.out.println("x2: " + x2.a);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- What is Java package
- How to define a Java package
- How to create a hierarchy of packages
- How to map Java package to directory