Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Essential Java Utility APIs and Overriding Object Class Methods

Tools 2

Java Utility APIs

API documentation provides specifications for using Java's built-in classes and methods. The official reference can be found at: https://docs.oracle.com/en/java/javase/index.html

Characteristics of the Object Class

  1. Classes within the java.lang package are automatically imported and do not require explicit import statements.
  2. Each class corresponds to a single bytecode file.
  3. The toString() method returns a string representation of the object. By default, it prints a hash-based identifier, which is unique for distinct object instances.
  4. The default string representation consists of: fully_qualified_class_name@hashcode_in_hex

Example: Using Object Class Methods

package com.example.demo;

public class ObjectDemo {
    public static void main(String[] args) {
        // Non-static methods are invoked using object references
        // Create Object instances
        Object instanceA = new Object();
        Object instanceB = new Object();

        // Invoke hashCode() method
        int hashA = instanceA.hashCode();
        int hashB = instanceB.hashCode();
        System.out.println("Hash code of instanceA: " + hashA);
        System.out.println("Hash code of instanceB: " + hashB);
        System.out.println("--------------------------------");

        // getClass() returns the Class object representing the runtime type
        Class<?> classA = instanceA.getClass();
        Class<?> classB = instanceB.getClass();
        System.out.println(classA);
        System.out.println(classB);

        // toString() returns the string representation
        String strRepA = instanceA.toString();
        String strRepB = instanceB.toString();
        System.out.println(strRepA);
        System.out.println(strRepB);

        // equals() compares object references by default
        boolean areEqual = instanceA.equals(instanceB);
        System.out.println("Are instances equal? " + areEqual);
    }
}

Overriding Object Methods in JavaBean Classes

The default implementations of toString() and equals() in the Object class often need to be overridden to provide meaningful behavior for custom classes. Integrated Development Environments (IDEs) typically provide shotrcuts (e.g., Alt+Insert or right-click -> Generate) to automatically generate these overrides.

Example: Student Class with Overridden Methods

Student.java

package com.example.model;

public class Student {
    private int studentId;
    private String fullName;
    private int grade;

    public Student() {}

    public Student(int studentId, String fullName, int grade) {
        this.studentId = studentId;
        this.fullName = fullName;
        this.grade = grade;
    }

    // Getters and setters omitted for brevity

    @Override
    public String toString() {
        return "Student{" +
                "studentId=" + studentId +
                ", fullName='" + fullName + '\'' +
                ", grade=" + grade +
                '}';
    }

    @Override
    public boolean equals(Object comparisonTarget) {
        // Reference equality check for efficiency
        if (this == comparisonTarget) return true;
        // Null and type compatibility checks
        if (comparisonTarget == null || getClass() != comparisonTarget.getClass()) return false;
        // Cast and field-based comparison
        Student otherStudent = (Student) comparisonTarget;
        return studentId == otherStudent.studentId && 
               grade == otherStudent.grade && 
               fullName.equals(otherStudent.fullName);
    }
}

Test.java

package com.example.test;

import com.example.model.Student;

public class Test {
    public static void main(String[] args) {
        // Test toString()
        Student pupilOne = new Student(101, "Alex Johnson", 85);
        System.out.println(pupilOne); // Implicitly calls toString()
        System.out.println(pupilOne.toString()); // Explicit call

        // Test equals()
        Student pupilTwo = new Student(102, "Alex Johnson", 85);
        boolean result = pupilOne.equals(pupilTwo);
        System.out.println("Students are equal: " + result); // false due to different IDs
    }
}

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.