Jump to content

help in using methods available in Object class

- - - - -

  • Please log in to reply
3 replies to this topic

#1
csepraveenkumar

csepraveenkumar

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
class a{
int x;
void printthis(){
System.out.println("In calss a.");
}
}
class example52{
public static void main(String args[]){
a b=new a();
//b.x=1;
a c=new a();
b.x=1;
c.x=1;
String str=b.toString();
System.out.println(str+" "+b.equals(c));
}
}

the result of executing the above code is
a@9304b1 false

what does the first part of the result mean and why is the equals method returning false when both the objects b and c have been initialised to the same value?

#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts

Quote

what does the first part of the result mean
a@9304b1 means an instance of class 'a', which has an address 9304b1 (hexadecimal).
You need to Override the method public void toString() to get desired result, which is inherited from the Object class.

Quote

why is the equals method returning false
You need to Override the public void equals(Object o) method, which is also inherited from the Object class. Right now the hexadecimal addresses are being compared and computer has no idea that it should compare the x value, thus returning always false.
Implement the equals method in both classes, and return true in case the x values match.

#3
csepraveenkumar

csepraveenkumar

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
class a{
int x;
void printthis(){
System.out.println("In calss a.");
}
}
class example52{
public static void main(String args[]){
a b=new a();
b.x=1;
a c=b.clone();
//b.x=1;
//c.x=1;
String str=b.toString();
System.out.println(str+" "+c.equals(b)+" "+b.getClass()+" "+b.x+" "+c.x);
}
}
on compiling the above code i get the following error
example52.java:11: clone() has protected access in java.lang.Object
a c=b.clone();
     ^
example52.java:11: incompatible types
found   : java.lang.Object
required: a
a c=b.clone();
           ^
2 errors

what is the proper syntax of using clone() method?

#4
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
You need to Override the public Object clone() method in your class, which, transfers the values to a new object.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users