Definition of Object and Class in Java
The Object class is the foundation of the Java programming language and has been present since JDK 1.0. All Java classes inherit the traits and methods of the Object class, whether directly or indirectly. For example, if a class C1 extends another class C2, then C1 inherits from the Object class indirectly because it is the ultimate parent class of all classes. If a class does not specify a parent class, it implicitly extends the Object class. Therefore, every data type in Java is a subclass of the Object class, making it a universal container for objects of different data types. In essence, an object of the Object class can hold any data.
Table of Contents
- Definition
- How do Object and Classes work in Java?
- How to Create an Object in Java?
- Characteristics of Objects in Java
- Properties of Object in Java
- Rules for Objects in Java
- Methods of Object Class in Java
How does Object Class work in Java?
The Object/class is located in the java.lang package is the highest class in the Java class hierarchy. Every category in Java is either a direct or indirect descendant of this class, which means that all classes inherit the instance methods that are defined in the Object class. Although it is not mandatory to override these inherited methods, it is common to do so to customize their behavior for specific classes. Additionally, the Object class can be utilized as a reference type in instances where the data type of an object is unknown, enabling the use of upcasting. You can downcast the Object reference to the appropriate class type if necessary to work with it as its original type.
How to Create an Object in Java?
If you are familiar with Java programming, you may know that an object is created using a class in Java. The class is nothing, but it provides a blueprint for creating an object. In Java, we declare the class before creating an object because the class is used to instantiate an object.
Let’s see the syntax of creating an object:
Syntax:
ClassName objectName = new ClassName();
- The syntax is simple and easy to understand. It starts with the class name for which we declare an object, followed by the name. The object name is nothing, but it is similar to declaring a variable name with the user-preferred name. This process of defining an object with a name is called an object declaration in Java.
- Object declaration is followed by an equal to (=) sign, assigning the object’s reference to our declared object variable. The new keyword is used for creating the new object. This new keyword will create a new object using the blueprint, i.e., class, and will allocate memory for the object. This creation of a new object is called object instantiation in Java.
- The new keyword is then followed by the method or the constructor of the class. The new keyword will call the constructor of the class automatically while creating a new object; this process is known as object initialization in Java.
We can also declare a different way. First, we will declare it, and then we can initialize it.
ClassName objectName; // Declarationobject
Name = new ClassName(); // Initialization
Every time we create a new object in Java, it allocates memory for the newly created object and returns the reference of that object to the object variable. This object reference can then perform different actions related to an object. Object reference here is nothing but corresponds to the newly declared object variable name.
Characteristics of Objects in Java
- Every object in Java will have its own identity. No two objects will have the same identity. Every object will correspond to a different memory location, and the address of the memory location will not be available to the user.
- An object will have its type associated with it. Every object will have a data type as a class.
- An object will also have two states and behaviors declared in it. These things are declared in class itself. The state will define attributes, and behavior will define the actions related to the class.
Properties of Object in Java
When defining a class in Java, we define the main two things. The first represents the attribute or state. This is known as the properties of an object. The properties are nothing, but the specific d is related to the class. Everything, when created, will have these properties available with it. We can access these properties in the class or outside by using the object reference depending upon the modifier used for it. As the object resembles a real-time entity, properties represent the state of an entity. For example, an object of Mobile may have a property like size, weight, etc. We allocate different memory locations for each property related to the object we create.
Rules for Objects in Java
- No such hard rules declare any object, but we should follow the standJava java naming convention while declaring the object name.
- We can access the methods of a class only by object reference or by class reference in special cases. Still, in both situations, we cannot access or modify the implementation of methods.
- We can reuse the once-defined object as many times as we want.
- We can easily remove or replace the objused depending upon the requirement.
Methods of Object Class in Java
Below is the list of instance methods available in the Object class:
1. toString()
Syntax:
public String toString()
This function extracts the string representation of an object, allowing users to modify it according to their needs easily. For, in case a class Office needs, the head of that branch must be displayed with location whenever one calls this function. , Thus, representation depends entirely on the object and is useful while debugging.
2. hashCode()
Syntax:
public int hashCode()
This function returns the hexadecimal representation of the object’s memory address, which helps compare two objects, as objects are considered equal only when their hashcodes match, as implemented in the Object class. But if one overrides the equals() method of the Object class, super implementation becomes inactive for that class’s objects.
3. equals(Object obj)
Syntax:
public boolean equals(Object obj)
This method overrides the default implementation of the equals method to compare two objects using their hashcode and returns true or false according to how you want to implement your logic to compare two objects of your class; you must override the equals method.
4. getClass()
Syntax:
public final Class getClass()
This method returns the reference of a Class object that helps to retrieve various information about the current class. Below are examples of instance methods of Class
- getSimpleName(): Returns the name of the class.
- getSuperClass(): Returns the reference of the superclass of the specified class.
- getInterfaces(): Returns the array of references of Class type for all the interfaces implemented in a specified class.
- isAnnotation(): Returns True is the specified class is an annotation otherwise false.
- getFields(): Returns the list of fields of the specified class.
- getMethods(): Returns the list of instance methods of the class.
5. finalize()
Syntax:
protected void finalize() throws Throwable
The JVM calls this method when it no longer has any references to the object, allowing for garbage collection. The Object class doesn’t define anything in the finalize function, and it doesn’t return anything. Subclasses can implement this method to perform some action, but they should not rely on knowing when it will invoke it, as the thread invoking it does not hold a user-visible authentication lock.
Any exception that occurs during the execution of finalize() halts it, so it needs to be handled with caution.
6. clone()
Syntax:
protected Object clone() throws CloneNotSupportedException
Subclasses should override this method when implementing the Cloneable Interface. This method is responsible for cloning, i.e., creating a copy of the object with values in member variables using the syntax obj.clone(). If a class does not implement the Cloneable interface, it will result in a CloneNotSupportedException being thrown.
By default, this method checks for the implementation of the Cloneable interface. However, if you wish to override this method according to your logic, you can do so using the following syntax:-
protected Object clone() throws CloneNotSupportedException
or
public Object clone() throws CloneNotSupportedException
Example:
package Try;
public class Desk implements Cloneable{
private int id;
private String Mid;
Desk(int id,String mid){
this.id=id;
this.Mid = mid;
}
@Override
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
@Override
public int hashCode()
{
return id;
}
public boolean equals(Desk dd){
return this.id == dd.id;
}
@Override
protected void finalize()
{
System.out.println("Lets call Fialize");
}
@Override
protected Desk clone() {
return this;
}
public static void main(String[] args){
Desk d1=new Desk(123,"344");
Desk d2=new Desk(234,"344");
System.out.println("toString Representation " + d1.toString());
System.out.println("HashCode for this object "+d1.hashCode());
System.out.println("Comparing 2 objects using equals method "+ d1.equals(d2));
Desk d3=d2.clone(); // cloning d2 object
System.out.println("Comparing clone object with original "+d2.equals(d3));
d1=d2=d3=null;
System.gc();
}
}
Output:
The use of three methods of the Object class is necessary when implementing multithreading behavior and requiring synchronization between different threads.
7. wait()
This method puts the current thread in the waiting state until any other thread is notified. The time needs to be specified in the millisecond function for which you need to resume the thread execution. There are three definitions for this function, as given below:
- public final void wait()
- public final void wait(long timeout)
- public final void wait(long timeout, int nanos)
8. notify()
Syntax:
public final void notify()
9. notifyAll()
This method wakes up all the threads waiting in the waiting queue.
Syntax:
public final void notifyAll()
Conclusion
Object class is topmost in the class hierarchy of every class in Java; thus, every class inherits its instance methods and can use them after overriding them according to the scenarios. Also, its object can be used as a reference variable for every class object using the upcasting concept.
Recommended Articles
We hope that this EDUCBA information on “Object and Class in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.