Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java class question

Tags:

java

class

class One {
public One foo() { return this; }
}

class Two extends One {
public One foo() { return this; }
}

class Three extends Two {
public Object foo() { return this; }
}

public Object foo() { return this; } throws a compilation error. Why is that? Can someone explain why "Object" type is not possible? Is Object the base class of Class One, Two? If So why does it throws an error?

Please change the title of the question as I couldnt find a suitable title.

like image 395
Shoban Avatar asked Nov 29 '22 05:11

Shoban


1 Answers

Three.foo is trying to override Two.foo(), but it doesn't do it properly. Suppose I were to write:

One f = new Three();
One other = f.foo();

Ignoring the fact that actually Three.foo() does return a One, the signature of Three.foo() doesn't guarantee it. Therefore it's not an appropriate override for a method which does have to return a One.

Note that you can change the return type and still override, but it has to be more specific rather than less. In other words, this would be okay:

class Three extends Two {
    public Three foo() { return this; }
}

because Three is more specific than One.

like image 120
Jon Skeet Avatar answered Dec 09 '22 15:12

Jon Skeet