Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals method" Watch "equals method" New topic
Author

equals method

Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
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

Joined: Aug 03, 2008
Posts: 9291
    
  17

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..


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
arulk pillai
Author
Ranch Hand

Joined: May 31, 2007
Posts: 3219
You can definitely override. You can reduce the visibility of the access modifier. That is from public to protected, etc.


Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

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.


[My Blog]
All roads lead to JavaRanch
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals method
 
Similar Threads
How to Use Comparator or BeanPropertyUtil to sort by multiple criteria
Problem with refresh() method of EntityManamger in JPA
Overloading (and NOT overriding) equals() method
que on equals()
HashMap entries with duplicate keys...