-1

I have this code in java and I do not understand the meaning of the Object in the following code ...

Here is the code

public class Tester {
    public static void main(String[] args) {
        Foo foo1 = new Foo(1);
        Foo foo2 = new Foo(2);

        System.out.print(foo1.equals(foo2));
    }
}

class Foo {
    Integer code;

    Foo(Integer c) {
        code = c;
    }

    public boolean equals(Foo f) {
        return false;
    }

    public boolean equals(Object f) {
        return true;
    }

}

When I run the code I get false but when I remove

public boolean equals(Foo f) {
        return false;
    }

and run the code I get true... Why is that and what is happening ?

Thanks

Reto
  • 1,305
  • 1
  • 18
  • 32

4 Answers4

3

This is method overloading resolution. There are two method candidates, one that takes an Object and the other takes Foo, when you pass a Foo, the most specific method (the one that takes Foo) will be called.

When you remove the method that takes Foo, you won't have an overload any longer and because Foo is an Object (as any class in Java) the method will accept it.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
1

Method Overloading. Most specific method gets chosen at run time.

As per Language specification most specific method chooses at run time.

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

You are getting false because most specific method got choosen. That is the reason

 public boolean equals(Foo f) {
        return false;
    }

This method called and returning false. When you remove this method,

 public boolean equals(Object f) {
        return true;
    }

This gets called because every Foo is Object.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

Because the compiler is going to invoke the most-specific method matching the parameters. When you have equals(Foo) that is more specific than equals(Object). When you remove equals(Foo) the equals(Object) is the only method that is still valid. It is also worth noting that Foo has an implicit parent class, java.lang.Object.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
-1

i think you don,t really understand object oriented programming, you should get a book on OOP to understand the consepts. check it-ebboks.com for some helpfull books

An objact is an instance of a class, take for instance a classroom of student offering the same subjects , if john doe is a memebr of that class that is he offers the courses in that class he is an instance of that class

public boolean equals(Foo f) {
    return false;
}  

is returning false no mattter what parameter you pass into it

Agbalaya Rasaq
  • 125
  • 1
  • 10