×

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is therefore extended by all Java classes. In order to inherit the class, we do not need to write the following statement.

Class Main extends object

Internally, the subclass inherits all of the Object class's methods. As a result, we can argue that Java's Object class is the universe's superclass. The java.lang package contains the class.

Java Object Class: Any object of any kind may be referenced by a variable of type Object belonging to the Cosmic Superclass.

Two objects that point to the same memory are tested using the Object class' equals() function.

If we wish to define an object's equality on our own, we must override the equals() method.

Replace the default function toString()method to print the class's representation.

The Java compiler calls the function toString() function every time an object is concatenated to a String with the "+" operator.

To print the class name and an object's memory location, the Object class provides the function toString()method.

Trace debugging is made easy with the function toString()technique.

MethodDescription
ObjectClone()It makes an object's copy.
boolean equals(Object obj)Determines whether two objects are equal. This  technique compares the references of two variables rather than the contents of two objects.
String toString()It returns a string representation of the object when you call string function
int hashCode()Integer is returned within the range

Compare objects in Java

The super class of all Java classes is the Java Object class. By default, every Java class implements the Object class. The equals() and hashCode() methods for comparing two Java objects are provided by the Java Object class. This section explains the operation of the equals() and hashCode() methods.

Program to compare to objects of class

Compare.java

// importing required packages 
// import util package to take the user input during run time using scanner class
import java.util.*;
import java.io.*;
// class 
public class Compare  
{    
// Main section of the program where execution of the program starts
public static void main(String args[])     
{    
// creating object for Scanner class with name sc
System.out.println(" Enter the strings which need to be compared ");
Scanner sc = new Scanner ( System . in ) ;
// Accessing the object of the Scanner class to take the inputs from the user
// Storing the inputs in string variable s1
String s1 = sc . next ( ) ;
// Storing the inputs in string variable s2
String s2 = sc . next ( ) ;
// Storing the inputs in string variable s3
String s3 = sc . next ( ) ;
// Checking the reference ids of two strings s1 and s2
System.out.println( " Are s1 and s2 strings are equal "+ s1.equals(s2) ) ;  
// Checking the reference ids of two strings s2 and s1
System . out . println  ( " Are s2 and s1 strings are equal "+ s2.equals(s1) ) ;  
// Checking the reference ids of two strings s2 and s3
System . out . println ( " Are s3 and s2 strings are equal "+ s2.equals(s3) ) ;   
}    
}  

Output

Cosmic Superclass in Java

ToString()

To return a string representation of an object, use the function toString() { [native code] } function. The function toString() function is internally called by the Java compiler whenever any object is printed. If not, the function toString()  function that was user-implemented or modified is invoked.To represent  the object in string  the function toString () is used .

Program to convert into strings

ConvertStrings.java

 // importing the necessary package
import java.util.*;
public classConvertStrings  
{    
int c; 
// default constructor for the program
ConvertStrings()     
{     
// Creating Scanner classs object to read the inputs
Scanner sc=new Scanner(System.in);
// storing the value in integer variable a
int a=sc.nextInt();
// storing the value in integer variable b
int b=sc.nextInt();
System.out.println("The sum of integers is: ");    
// caluclating the sum of a and b
c=a+b;    
System.out.println("The sum is: "+c);            
}         
// Main section of the code where execution of the program starts
public static void main(String args[])     
{     
// creating object for the Main class with name o1
Main o1 = new Main();      
System.out.println(o1.toString());     
}      
}   

Output

Cosmic Superclass in Java

Object Clone

The most crucial activity in Java is making a copy or clone of an object. A reference copy, as the name suggests, creates a duplicate of a reference variable referring to an object. For instance, if we create a reference copy of a Byke object that already has a myByke variable referring to it, the original object will still exist.A copy of an object is made of the actual object. Therefore, if we cloned our byte object once again, we would make a copy of the object and a second reference variable that pointed to it.A shallow duplicate of an object is a brand-new object with the same instance variables as the original object. A shallow clone of a Set, for instance, shares objects with the original Set by pointers and has the same members as the original Set. It's sometimes claimed that shallow copies employ reference semantics. references are replicated just superficially. As a result, the reference is the same for both the original and the object. the process of creating a new reference to the same memory location. Keep in mind that any modifications we make to the data in the cloned object also affect the original.

Advantages  of object cloning

• Object. Despite these design issues, clone() is still a frequently used and straightforward technique of cloning objects.

• Long, repetitive codes are not required.

• Only use abstract classes with 4- or 5-line clone() methods. It is the easiest and most efficient way to duplicate stuff, especially if we're integrating it to an old or older project.

Simply constructing a parent class, including Cloneable implementation, and supplying the definition of the clone() function will suffice to finish the task.

• Using clone is the easiest way to duplicate an array ().

Disadvantages  of object cloning

• To utilise the Object.clone() function while implementing a Cloneable interface, declare the clone() method, solve the CloneNotSupportedException, and afterwards call Object.clone().

• Despite the fact that it lacks methods, we still have to create a cloneable interface. We merely need to make use of it to let the JVM know that we can clone() our object.

We must provide our own clone() and call Object.clone() indirectly from it since Object.clone() is protected.

We have really no control about how an object is created since Object.clone() does not invoke any function Object().

Program for cloning objects

Clone.java

class Clone implements Cloneable {  
int id ;  
String s ;  
Clone ( String s , int id ) 
{  
this . id = id ;  
this. s = s ;  
}  
public Object clone ( ) throws CloneNotSupportedException
{  
return super . clone ( ) ;  
}  
public static void main ( String args [ ] )
{  
try  {  
Clone s1=new Clone ( "Rohith" ,9 ) ;  
Clone s2 = (Clone)s1 . clone ( ) ;  
System . out . println ( " Name is " + s1 . s+ "  and rollno is " + s1 . id );  
System . out . println ( " Name is " + s2 . s + " and rollno is " + s2 . id ) ;  
} catch ( CloneNotSupportedException c )
{
}  
}  
}

Output

Cosmic Superclass in Java

Hashcode

The hash code for the supplied inputs is returned by the Java Integer class function hashCode(). Java's hashCode() function comes in two varieties that may be distinguished by their respective parameters.

hashCode() Technique

The Java Integer Class's hashCode() function finds the hash code for a specified Integer. In the class Object, it overrides hashCode. This function by default produces a random, instance-specific number.

 hashCode(int value)

A hash code is generated for a given int value using the built-in Java Integer Class function hashCode(int value). Integer and this technique work together. hashCode().

Code for hashcode program

import java.io.*;
import java.util.*;
public class IntegerHashCode {  
    public static void main ( String[] args )  
    {  
        
        Integer r = new Integer ( "113" ) ;           
        int hashValue = r . hashCode ( ) ;  
        System . out . println ( "Hash code Value for object is: " + hashValue ) ;  
    }  
}  

Output

Cosmic Superclass in Java

HashCode2.java

import java.util.Scanner;  
public class HashCode2{  
    public static void main(String[] args) {  
      System.out.print("Enter the desired input value: ");  
      Scanner sc = new Scanner(System.in);         
        Integer i = sc.nextInt();  
        sc.close();  
        int h = Integer.hashCode(i);  
        System.out.println("Hash code Value for object is: " + h);  
        }  
}  

Output

Cosmic Superclass in Java

Related Topics

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.