<< Hide Menu
Avanish Gupta
Milo Chang
Avanish Gupta
Milo Chang
Now that we have learned about inheritance, what even allows our classes and objects that we have created to work the way they do? Where do the general characteristics of all objects come from? The answer lies in the Object class.
The Object class is the superclass of all other classes as well as arrays and other data types. The Object class is part of the java.lang package.
When we call a constructor to a "top-level class" that the coder hasn't declared a superclass for, the Object constructor is implicitly called. In other words, the Object constructor is implicitly called when we call a constructor in a class that doesn't explicitly extend another class. This will give the object some properties and methods that are common to all classes.
In the Object class, there are also a few methods that are provided by default. The three that we will look at are as follows:
The hashCode() method returns what is known as a hash code, an integer that is used to represent the memory location of the object. This is usually based on the properties of an object and any two objects with the same properties should have the same hash code.
This goes along with the equals() method that we first learned about in Unit 3. This method determines whether two objects are equal to each other based on whether they have the same properties or not. If two objects are determined to be equal, then they must have the same hash code.
Finally, we have the toString() method from Unit 5. This method returns a string representation of the object that the method is called on. This usually prints the properties of the object, but by default, the method returns objectName + "@" + hashCode() , which in most situations, does not give any useful information about an object.
For the three methods above to achieve their intended results, we usually override these methods and write our own class-specific implementation of these methods to make sure that the methods work the way we want them to.
© 2024 Fiveable Inc. All rights reserved.