Java 动态绑定和方法重写

昨天我进行了两个小时的技术电话面试(我通过了,呜呼!),但是我完全搞砸了下面关于 Java 中动态绑定的问题。更令人困惑的是,几年前我还是助教的时候,我曾经教过本科生这个概念,所以我给他们错误信息的前景有点令人不安... ..。

以下是我得到的问题:

/* What is the output of the following program? */


public class Test {


public boolean equals( Test other ) {
System.out.println( "Inside of Test.equals" );
return false;
}


public static void main( String [] args ) {
Object t1 = new Test();
Object t2 = new Test();
Test t3 = new Test();
Object o1 = new Object();


int count = 0;
System.out.println( count++ );// prints 0
t1.equals( t2 ) ;
System.out.println( count++ );// prints 1
t1.equals( t3 );
System.out.println( count++ );// prints 2
t3.equals( o1 );
System.out.println( count++ );// prints 3
t3.equals(t3);
System.out.println( count++ );// prints 4
t3.equals(t2);
}
}

我断言输出应该是来自重写的 equals()方法中的两个单独的 print 语句: 在 t1.equals(t3)t3.equals(t3)。后一种情况显而易见,对于前一种情况,即使 t1具有 Object 类型的引用,它也被实例化为 Test 类型,因此动态绑定应该调用方法的重写形式。

显然不是。我的面试官鼓励我自己运行这个程序,你瞧,这个被覆盖的方法只有一个输出: 在 t3.equals(t3)行。

我的问题是,为什么?正如我已经提到的,即使 t1是 Object 类型的引用(因此静态绑定将调用 Object 的 equals()方法) ,动态绑定 应该负责根据引用的实例化类型调用方法的最特定版本。我错过了什么?

44722 次浏览

I think the key lies in the fact that the equals() method doesn't conform to standard: It takes in another Test object, not Object object and thus isn't overriding the equals() method. This means you actually have only overloaded it to do something special when it's given Test object while giving it Object object calls Object.equals(Object o). Looking that code through any IDE should show you two equals() methods for Test.

The method is overloaded instead of overriden. Equals always take an Object as parameter.

btw, you have an item on this in Bloch's effective java (that you should own).

The equals method of Test does not override the equals method of java.lang.Object. Look at the parameter type! The Test class is overloading equals with a method that accepts a Test.

If the equals method is intended to override, it should use the @Override annotation. This would cause a compilation error to point out this common mistake.

Java does not support co-variance in parameters, only in return types.

In other words, while your return type in an overriding method may be a subtype of what it was in the overridden, that is not true for parameters.

If your parameter for equals in Object is Object, putting an equals with anything else in a subclass will be an overloaded, not an overridden method. Hence, the only situation where that method will be called is when the static type of the parameter is Test, as in the case of T3.

Good luck with the job interview process! I'd love to be interviewed at a company that asks these types of questions instead of the usual algo/data structures questions that I teach my students.

Interestingly enough, in Groovy code (which could be compiled to a class file), all but one of the calls would execute the print statement. (The one comparing a Test to an Object clearly won't call the Test.equals(Test) function.) This is because groovy DOES do completely dynamic typing. This is particularly of interest because it does not have any variables that are explicitly dynamically typed. I have read in a couple of places that this is considered harmful, as programmers expect groovy to do the java thing.

Java uses static binding for overloaded methods, and dynamic binding for overridden ones. In your example, the equals method is overloaded (has a different param type than Object.equals()), so the method called is bound to the reference type at compile time.

Some discussion here

The fact that it is the equals method is not really relevant, other than it is a common mistake to overload instead of override it, which you are already aware of based on your answer to the problem in the interview.

Edit: A good description here as well. This example is showing a similar problem related to the parameter type instead, but caused by the same issue.

I believe if the binding were actually dynamic, then any case where the caller and the parameter were an instance of Test would result in the overridden method being called. So t3.equals(o1) would be the only case that would not print.

The answer to the question "why?" is that's how the Java language is defined.

To quote the Wikipedia article on Covariance and Contravariance:

Return type covariance is implemented in the Java programming language version J2SE 5.0. Parameter types have to be exactly the same (invariant) for method overriding, otherwise the method is overloaded with a parallel definition instead.

Other languages are different.

It's very clear, that there is no concept of overriding here. It is method overloading. the Object() method of Object class takes parameter of reference of type Object and this equal() method takes parameter of reference of type Test.

Some note in Dynamic Binding (DD) and Static Binding̣̣̣(SB) after search a while:

1.Timing execute: (Ref.1)

  • DB: at run time
  • SB: compiler time

2.Used for:

  • DB: overriding
  • SB: overloading (static, private, final) (Ref.2)

Reference:

  1. Execute mean resolver which method prefer to use
  2. Because can not overriding method with modifier static, private or final
  3. http://javarevisited.blogspot.com/2012/03/what-is-static-and-dynamic-binding-in.html

I found an interesting article about dynamic vs. static binding. It comes with a piece of code for simulating dynamic binding. It made my code a more readable.

https://sites.google.com/site/jeffhartkopf/covariance

If another method is added that overrides instead of overloading it will explain the dynamic binding call at run time.

/* What is the output of the following program? */

public class DynamicBinding {
public boolean equals(Test other) {
System.out.println("Inside of Test.equals");
return false;
}


@Override
public boolean equals(Object other) {
System.out.println("Inside @override: this is dynamic binding");
return false;
}


public static void main(String[] args) {
Object t1 = new Test();
Object t2 = new Test();
Test t3 = new Test();
Object o1 = new Object();


int count = 0;
System.out.println(count++);// prints 0
t1.equals(t2);
System.out.println(count++);// prints 1
t1.equals(t3);
System.out.println(count++);// prints 2
t3.equals(o1);
System.out.println(count++);// prints 3
t3.equals(t3);
System.out.println(count++);// prints 4
t3.equals(t2);
}
}

I will try to explain this through two examples which are the extended versions of some of the examples that I came across online.

public class Test {


public boolean equals(Test other) {
System.out.println("Inside of Test.equals");
return false;
}


@Override
public boolean equals(Object other) {
System.out.println("Inside of Test.equals ot type Object");
return false;
}


public static void main(String[] args) {
Object t1 = new Test();
Object t2 = new Test();
Test t3 = new Test();
Object o1 = new Object();


int count = 0;
System.out.println(count++); // prints 0
o1.equals(t2);


System.out.println("\n" + count++); // prints 1
o1.equals(t3);


System.out.println("\n" + count++);// prints 2
t1.equals(t2);


System.out.println("\n" + count++);// prints 3
t1.equals(t3);


System.out.println("\n" + count++);// prints 4
t3.equals(o1);


System.out.println("\n" + count++);// prints 5
t3.equals(t3);


System.out.println("\n" + count++);// prints 6
t3.equals(t2);
}
}

Here, for lines with count values 0, 1, 2, and 3; we have reference of Object for o1 and t1 on the equals() method. Thus, at compile time, the equals() method from the Object.class file will be bounded.

However, even though reference of t1 is Object, it has intialization of Test class.
Object t1 = new Test();.
Therefore, at run-time it calls the public boolean equals(Object other) which is an

overridden method

. enter image description here

Now, for count values as 4 and 6, it is again straightforward that t3 which has reference and initialization of Test is calling equals() method with parameter as Object references and is an

overloaded method

OK!

Again, to better understand what method the compiler will call, just click on the method and Eclipse will highlight the methods of similar types which it thinks will call at the compile time. If it doesn't get called at compile time then those methods are an example of method overridding.

enter image description here