• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals method

 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Employee
{
int empid;
String name;
Employee(int id,String name)
{
this.empid=id;
this.name=name;
}

public int getEmpId()
{
return empid;
}


public String getString()
{
return name;
}



public boolean equals(Object o) //compilation error if public is not added
{
if ((o instanceof Employee) && (((Employee)o).getEmpId()
== this.empid))
{
return true;
}
else
{
return false;
}
}


}
class JavaBeat1
{
public static void main(String[] args)
{
Employee x1 = new Employee(1,"abc");
Employee x2 = new Employee(2,"def");
Employee x3 = new Employee(1,"abc");
if( x1.equals(x3) )
{
System.out.println("x1 and x3 are equal");
}
else
{
System.out.println("x1 and x3 are not equal");
}


}
}

As far as I know ,equals(java.lang.Object) in Employee cannot override equals(java.lang.Object) in java.lang.Object. But if I add public to the 'equals' method in Employee
it's giving the output x1 andx3 are equal.

can anyone explain me this in detail.

thanks in advance

Preparing Scjp5
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know ,equals(java.lang.Object) in Employee cannot override equals(java.lang.Object) in java.lang.Object.


Who said this . Of course you can override the equals method of Object class..
 
arulk pillai
Author
Ranch Hand
Posts: 3385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can definitely override. You can reduce the visibility of the access modifier. That is from public to protected, etc.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are not allowed to reduce the visibility of the overriden method, unless it is a static method (here changing a public method into a default access method). This is called "hiding" a method, and does not work on instance methods. Only static methods be be hidden.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic