Just play with the interfaces, and I have a question about something that I cannot understand.
The following code does not run, which is the behavior that I expect, since the interface method requires the method to work for any object, and the implemented method changed the signature to allow only string objects.
interface I {
public void doSomething(Object x);
}
class MyType implements I {
public void doSomething(String x) {
System.out.println(x);
}
}
However, using the following block of code, I was shocked to see that it really works. I thought this would not work, since we expect to return an object, and the implemented method will only return a string object. Why does this work and what is the difference between the two principles here for the parameters passed and return types?
interface I {
public Object doSomething(String x);
}
class MyType implements I {
public String doSomething(String x) {
System.out.println(x);
return(x);
}
}
mark source
share