Parent of All Classes
In many programming languages like Java, there is always a class that is implicitly the parent of all the built-in and user-defined classes. Java calls it the Object
class. The Object
class is beneficial if you want to refer to any object whose type you don't know. Notice that the parent class reference variable can refer to the child class object (defined as upcasting in the previous section). We can instantiate an Object
object using the following method:
1var obj = getObject();
The Object
class has many methods predefined in it, so any user-defined class should have those built-in methods in it without explicitly declaring or defining them. The methods are:
public final Class getClass()
public int hashCode()
public boolean equals(Object obj)
protected Object clone()
public String toString()
public final void notify()
public final void notifyAll()
public final void wait(long timeout) throws InterruptedException
public final void wait(long timeout,int nanos) throws InterruptedException
public final void wait() throws InterruptedException
protected void finalize() throws Throwable
Using this Object
class, we can create an array of Objects of any type. See the code below:
1var objects = [5, 5.5];
2console.log(objects[0]);
3console.log(objects[1]);
4// Output:
5// 5
6// 5.5
Remember that you need to remember the types when you insert them into the containers (arrays) or else there would be no way to know what that Object was previously.