-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEqualsWithInheritance.java
executable file
·71 lines (61 loc) · 1.69 KB
/
EqualsWithInheritance.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class BaseClass
{
public BaseClass( int i )
{
x = i;
}
public boolean equals( Object rhs )
{
if( EqualsWithInheritance.BROKEN )
{
// This is the wrong test (ok if final class)
if( !( rhs instanceof BaseClass ) )
return false;
}
else
{
// This is the correct test, if class is not final
if( rhs == null || getClass( ) != rhs.getClass( ) )
return false;
}
return x == ( (BaseClass) rhs ).x;
}
int x;
}
class DerivedClass extends BaseClass
{
public DerivedClass( int i, int j )
{
super( i );
y = j;
}
public boolean equals( Object rhs )
{
if( EqualsWithInheritance.BROKEN )
{
// This is the wrong test.
// Test is not needed if getClass() done in superclass equals
if( !( rhs instanceof DerivedClass ) )
return false;
}
return super.equals( rhs ) && y == ( (DerivedClass) rhs ).y;
}
int y;
}
public class EqualsWithInheritance
{
/**
* Change this variable. If true, equals is not
* symmetric. If false, it is.
*/
public static final boolean BROKEN = false;
public static void main( String [ ] args )
{
BaseClass a = new BaseClass( 5 );
DerivedClass b = new DerivedClass( 5, 8 );
DerivedClass c = new DerivedClass( 5, 8 );
System.out.println( "b.equals(c): " + b.equals( c ) );
System.out.println( "a.equals(b): " + a.equals( b ) );
System.out.println( "b.equals(a): " + b.equals( a ) );
}
}