Java-Overriding equals Method

Overriding equals Method

The equals( ) method compares two object reference, to see whether they refer to the same object.

Program : Without Overriding equals

 

The following example overrides equals() method .

Program : With Overriding equals


Program Source : Without Overriding equals

class Book {
    
    String name;
    
    Book(String na)
    {
        name = na;
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        Book bo1 = new Book("Hajsofjava");
        Book bo2 = new Book("Hajsofjava");
        if(bo1.equals(bo2))
            System.out.println("Both books author : hajsof");
        else
            System.out.println("false");
    }
}

Program Source : With Overriding equals

class Book {
    
    String name;
    
    Book(String na)
    {
        name = na;
    }
    
    public boolean equals(Object obj)
    {
        if(obj instanceof Book)
            return name.equals(((Book)obj).name);
        else
            return false;
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        Book bo1 = new Book("Hajsofjava");
        Book bo2 = new Book("Hajsofjava");
        if(bo1.equals(bo2))
            System.out.println("Both books author : hajsof");
        else
            System.out.println("false");
    }
}

Leave a Comment