Skip to content

Commit 69628ab

Browse files
authored
Add files via upload
1 parent 819d717 commit 69628ab

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Diff for: Methods/EqualsOverriding.java

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import javax.lang.model.util.ElementScanner6;
2+
3+
class Person
4+
{
5+
String name;
6+
int age;
7+
Person(String name,int age)
8+
{
9+
this.name=name;
10+
this.age=age;
11+
}
12+
}
13+
14+
class Person1 {
15+
String name;
16+
int age;
17+
18+
Person1(String name, int age) {
19+
this.name = name;
20+
this.age = age;
21+
}
22+
public boolean equals(Object o)
23+
{
24+
// If the object is compared with itself then return true
25+
if (o==this)
26+
{
27+
return true;
28+
}
29+
//Check if o is an instance of Person1 or not
30+
if (!(o instanceof Person1))
31+
{
32+
return false;
33+
}
34+
// typecast o to Person1 so that we can compare data members
35+
Person1 p=(Person1) o;
36+
return name.equals(p.name) == true && Integer.compare(age, p.age) == 0;
37+
38+
}
39+
}
40+
41+
class EqualsOverriding
42+
{
43+
public static void main(String[] args) {
44+
45+
Person p1=new Person("Disha",22);
46+
Person p2 = new Person("Disha",22);
47+
if (p1==p2)
48+
{
49+
System.out.println("Equal");
50+
}
51+
else
52+
{
53+
System.out.println("Not Equal");
54+
}
55+
System.out.println("The reason for printing “Not Equal” is simple: when we compare p1 and p2, it is checked whether both p1 and p2 refer to same object or not.p1 and p2 refer to two different objects, hence the value (p1 == p2) is false. If we create another reference say p3 like following, then (p1 == p3) will give true.\nPerson p3 = p1");
56+
57+
System.out.println("After Overriding equals() method");
58+
Person1 p11=new Person1("Disha",22);
59+
Person1 p21 = new Person1("Disha",22);
60+
if(p11.equals(p21))
61+
{
62+
System.out.println("Equal");
63+
}
64+
else{
65+
System.out.println("Not Equal");
66+
}
67+
}
68+
69+
}

0 commit comments

Comments
 (0)