let's have dog
class has field private final int age
, method public dog ageby(time time)
returns new instance of dog every time invoked. dog
class not immutable doesn't have get
methods return it's age, in other words dog's contract doesn't allow him age (why? cause there no talking dogs), can 'bark', 'sleep' , other dog's stuff.
but dog
can compared other dogs age. need override public equals(object o)
method in dog
class. problem there no way compare it, because can't access passed dogs age.
question: how implement equals method without exposing fields of object?
any method can access private
fields of same class, can write equals accessing directly fields, without needs of getters.
here example:
public class point { private int x; private int y; public point (int x, int y) { this.x = x; this.y = y; } public boolean equals(object obj) { // test null, , type ... point p = (point) obj; return x == p.x && y == p.y; }
Comments
Post a Comment