1

I don't understand why in Point class where I call the method on an object , it returns false. So, in method, in third/fourth/fifth case it returns false even if values of x and y of every objects are zero.

class Point{
    private int x;
    private int y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

public boolean method(Point p) { 
     if (p!=null)    
         return x==p.x && y==p.y;   
     else return false;  
}

}

public class AppPoint{
    public static void main(String[] args) {
        Point p = new Point (0, 0);
        Point q = new Point (0, 0);
        Object r = new Point (0, 0);
        Object s = new Point (0, 0);
        System.out.println(p.method(p));
        System.out.println(p.method(q));
        System.out.println(p.method(r));
        System.out.println(r.method(q));
        System.out.println(r.method(s));
    }
}

// method return: true true false false false
Megan
  • 43
  • 5
  • interesting because for r as it is an object does not know that equals2 exists – vmrvictor Jul 13 '20 at 14:07
  • _Always_ use `@Override` for intended method overrides. – chrylis -cautiouslyoptimistic- Jul 13 '20 at 14:16
  • You are not supposed to edit a question such that it invalidates an answer. You changed your incorrect equals method to an equally silly method method, making rzwitserloot answer unintelligable. – NomadMaker Jul 13 '20 at 14:37
  • Cosa avrei dovuto fare dato che mi hanno segnalato la domanda come duplicata e il mio dubbio è rimasto . La risposta sotto era corretta ma non mi risolve il mio problema. Mi interessava solo il motivo per cui stampasse true e false , non il fatto dell'override. @NomadMaker google translate – Megan Jul 13 '20 at 14:49

1 Answers1

3

In java, the signature alone defines a method's identity.

Object's equals method has this signature:

boolean equals(Object other).

That means your equals method is a completely different one. For a method to be an override of a parent's method, all relevant parts of the signature need to match, which notably includes the types of the parameters.

A good way to ensure you don't mess this up: Add @Override for all methods which you think override something. If they don't, the compiler will inform you about the mismatch between what you think your code means and what it actually means. Try it! Add this annotation; you'll notice your IDE and javac compile run will complain about it. Then upgrade your arg to Object instead of Point.

NB: p.equals(r) does work because javac compiles that as a call to your Point's equals method. Nevertheless, you really don't want this confusion, where Object's equals method and Point's equals method don't have the same signature.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72