Overriding equal method

In java when we use equals method to compare two objects it returns true only if these referring to same memory location.

Code

public class OverrideEqual{
public static void main(String[] args){
Person p1= new Person("John",17);
Person p2= new Person("John",17);
if(p1.equals(p2)){
System.out.println("p1 equals to p2");
}else{
System.out.println("p1 is not equals to p2");
}
}
}

class Person{
String name;
int age;
        Person(String name,int age){
this.name=name;
this.age=age;
}
}

Output:
 p1 is not equals to p2

So if we want to compare two objects according to the states or values then we have to override the equals method.

Code:

public class OverrideEqual{
public static void main(String[] args){
Person p1= new Person("John",17);
Person p2= new Person("John",17);
if(p1.equals(p2)){
System.out.println("p1 equals to p2");
}else{
System.out.println("p1 is not equals to p2");
}
}
}

class Person{

String name;
int age;

       Person(String name,int age){
this.name=name;
this.age=age;
}

      @Override
       public boolean equals(Object obj){
if(obj==this){
return true;
if( !(obj instanceof Person) ){
return false;
Person p=(Person)obj;
             
               if(this.name==p.name && this.age==p.age){
return true;
}
               return false;
}
}

Output:
p1 equals to p2




Comments

Popular posts from this blog

Flow Charts

ධර්මය, ආක්‍රමණය හා යුද්ධය

ආගමක් නැති මනුස්සයෙක්