Reputation: 2653
Just getting into some Java for now. Saw this extended class in the OCA 7 book and just wondered how it's possible that class Baz uses the go method and expects return type String but the argument takes an int. The return is then null.
Is Baz a legal construction or will this return compile error? I mean it returns type String, but takes an int argument and then returns null. How is that possible?
public class Foo {
void go() {}
}
public class Baz extends Foo {
String go(int x) {
return null;
}
}
Upvotes: 0
Views: 66
Reputation: 8301
Since Baz
extends Foo
it will inherit Foo
's go()
method.
Additionally Baz
declares its own method called go(int x)
with a return type of String
. These are two different methods and the compiler treats them as such, since they have a different signature (= name + parameter types). If the only difference was the return type then you'd get a compilation error.
Because the signature is different the compiler can always tell which method you want to call - in this case depending on whether you pass an int
as a parameter when calling go
or not.
This is why Baz
is a fully valid Java class.
Edit: go(int x)
can return null
because String
is a class. You can always pass/return null
when a reference to an instance of a class is expected. (The method parameter doesn't matter at all for why this is possible)
Upvotes: 2