Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing private variables in equals()

 
Jagdish Shinde
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am trying to compare two objects by overriding equals(Object o) method.
Code:
public class TestEquals{
private int a;
private int c;
private boolean val=false;
public boolean equals(Object o){

TestEquals te=null;
if(o instanceof TestEquals)
{
te = (TestEquals)o;
if((this.a==te.a)&&(this.c==te.c))
val=true;
else val= false;
}

return val;
}

How can I access private variables a&c using te.a and te.c??
I thought i need to write getters for this.
(And this is valid for any method (other than equals())in TestEquals) class )

Please help..

Thanks.
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jagdish Shinde:
Hello,
How can I access private variables a&c using te.a and te.c??
I thought i need to write getters for this.
(And this is valid for any method (other than equals())in TestEquals) class )

Thanks.


just create getter for the variable a & c and use them to access private variable. Getter should be public method returning the variable.
 
Jagdish Shinde
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if((this.a==te.a)&&(this.c==te.c))

I thought i wont be able to access private variables a & c using te.a and this line would cause compilation error. But it is compiling with this line.
My question is, since a & c are private I would be restricted from using '.' operator to access a,c and a public getter was needed. but it is compiling fine.
Is this some special case!?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jagdish Shinde:
if((this.a==te.a)&&(this.c==te.c))

I thought i wont be able to access private variables a & c using te.a and this line would cause compilation error. But it is compiling with this line.
My question is, since a & c are private I would be restricted from using '.' operator to access a,c and a public getter was needed. but it is compiling fine.
Is this some special case!?


No, it's not a special case. Access modifiers work on the class level, not on the instance level. So, private members can be accessed from anywhere inside the same class, no matter what object they belong to.
 
Jagdish Shinde
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ilja,
I got the point.

This probably worked because the reference 'te' used was of the same class TestEquality where I was accessing private variables.


Thanks...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic