Java Interface Methods

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); 
    }
}
+3
source share
8
public Object doSomething(String x);

- . , , - . ,

public String doSomething(String x) {stuff}

, . , , , , .

, , , , . .

, , , , . , , , , , , . 6 ( , String, ), . ( ) , , .

+3

, String Object.

+2

java:

, , . - , .

, , , , - String, - Object.

+2

. "" .

, String Object, Object String.

+2

, , - , , . , , .

, (String - Object), .

, .

, Java , .

:

interface I<T>
{
    public void doSomething(T x);
}

class MyType implements I<String>
{
    public void doSomething(String x)
    {
        System.out.println(x);
    }
}
+1

. ( is is error, , ). :

void doSomething(Object)
void doSomething(String)

These are just two methods, and none of them overrides or implements the others.

+1
source

The string class inherits from the class of the object, so only this code works.

+1
source

All Articles