Object Class Methods

Object class:
  • It is superclass of all the classes in java
  • It is present in java.lang package
  • It consists of 11 methods
    e.g.
    getClass(), hashCode(), equals(Object obj), clone(), toString(), notify(), notifyAll(), wait(), wait(long), wait(long, int), finalize()
  • 6 methods are final methods
    e.g.
    getClass(), notify(), notifyAll(), wait(), wait(long) and wait(long, int) these methods cannot be overridden

ObjectClass.java
package com.core.java;

public class ObjectClass implements Cloneable {
    static ObjectClass obj;
    static Object obj1;

    public static void main(String[] args) {
        obj = new ObjectClass();

        // Get name of class from which object is created
        System.out.println("Class Name is: " + obj.getClass().getName());

        // display a hash code of the object
        System.out.println("" + obj.hashCode());

        // display the string format of the object
        // by default toString() method will invoke
        System.out.println(obj);
        System.out.println(obj.toString());

        // Get a duplicate of the object
        try {
            obj1 = obj.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        System.out.println(obj1.hashCode());
        System.out.println(obj1);
        System.out.println(obj1.getClass());

        System.out.println(obj.equals(obj1));

        ObjectClass obj2 = obj;
        System.out.println(obj.equals(obj2));

        int[] array = { 1, 2, 3, 4, 5 };
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }

        // Array is an Object
        obj1 = array;
        System.out.println("\n" + obj1);

        // Object is a super class of all the classes
        String str = new String("Demo");
        obj1 = str;
        System.out.println(obj1);
    }
}

Output:
Class Name is: com.java.ObjectClass
366712642
com.java.ObjectClass@15db9742
com.java.ObjectClass@15db9742
1829164700
com.java.ObjectClass@6d06d69c
class com.java.ObjectClass
false
true
1 2 3 4 5
[I@7852e922
Demo

Finalize.java
package com.java;

public class Finalize {
    int id;
    String name;
    public void finalize(){
        id = 0;
        name ="";
        System.out.println("Finalize method is called");
    }
    public String toString(){
        return "Id: " + id + " and Name: " + name;
    }
    public static void main(String[] args) throws Throwable {
        Finalize f1 = new Finalize();
        f1.id = 111;
        f1.name = "Shyam Sunder";
        System.out.println(f1);
        f1.finalize();
        System.out.println(f1);
    }
}

Output:
Id: 111 and Name: Shyam Sunder
Finalize method is called
Id: 0 and Name: 

No comments:

Post a Comment