πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

πŸ–²

9.7 Object Superclass

2 min readβ€’june 18, 2024

Milo Chang

Milo Chang

Avanish Gupta

Avanish Gupta


AP Computer Science AΒ πŸ’»

130Β resources
See Units

Introduction to the Object Superclass

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.

Object Methods

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:
  • hashCode()
  • equals()
  • toString()

hashCode()

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.

equals()

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.

toString()

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.
Browse Study Guides By Unit
βž•Unit 1 – Primitive Types
πŸ“±Unit 2 – Using Objects
πŸ–₯Unit 3 – Boolean Expressions & if Statements
πŸ•ΉUnit 4 – Iteration
βš™οΈUnit 5 – Writing Classes
⌚️Unit 6 – Array
πŸ’ΎUnit 7 – ArrayList
πŸ’»Unit 8 – 2D Array
πŸ–²Unit 9 – Inheritance
πŸ–±Unit 10 – Recursion
🧐Exam Skills

Fiveable
Fiveable
Home
Stay Connected

Β© 2024 Fiveable Inc. All rights reserved.


Β© 2024 Fiveable Inc. All rights reserved.