Java override doubt
In the following program in the main method an anonymous class which implements the interface TestInt is inst开发者_运维百科antiated and printed.
On printing any object, its class's toString method is invoked. But the class Foo which also extends Object which has got a public String toString() method and so does the testInt interface. So which function are we overriding in main ? The one from Object or one from TestInt ?
interface TestInt{ String toString(); }
public class Foo {
public static void main(String[] args) {
System.out.println(new TestInt() {
public String toString() { return "foo"; }
});
}
}
The program above compiles and runs fine and generates "foo" as output.
You're overriding Object#toString()
and implementingTestInt#toString()
. But that's a very nit-picky distinction. Since the methods have the same signature, they are for all practical purposes the same.
You are implementing TestInt
's toString()
method and overriding Object
's toString
method. The TestInt
interface dictates that any class that implements it must also implement the toString()
method which you likely don't have to do because by nature of being a subclass of Object
you already implement. An important thing to remember is inheritance is a hierarchy. If your parent implements a method, and you implement a method with the same signature, then you override your parent. It doesn't matter if your parent happens to override its parent and so on. However, you could override a method of your grandparent that your parent chooses not to override. For example,
public class Foo{
public void myMethod(){
System.out.println("Foo.myMethod");
}
public void anotherMethod(){
System.out.println("Foo.anotherMethod");
}
}
public class Bar extends Foo{
public void myMethod(){
System.out.println("Bar.myMethod");
}
}
public class Bazz extends Bar{
public void myMethod(){
System.out.println("Bazz.myMethod");
}
public void anotherMethod(){
System.out.println("Bazz.anotherMethod");
}
}
In this case, Bar
subclasses Foo
and overrides the Foo.myMethod
method but does not override the Foo.anotherMethod
method. Bazz
in turn subclasses Bar
and overrides Bar.myMethod
and Foo.anotherMethod
. In reality, you would say that it overrides Bar.anotherMethod
because, although in this instance we know that Bar
doesn't implement anotherMethod
, in the real world you wouldn't know and wouldn't care whether it did or not. You simply know that the class Bar
has the method anotherMethod.
I would say both, but you didn't actually implement this interface... Interface is a purely abstract class, therefore all its method are not implemented... So you provide an implementation and it is visible both as interface method implementation (so you can refer to it having reference to interface) as well as it is overridden version of Object's toString()...
精彩评论