简体   繁体   中英

Java class method defines String type, takes int as param and returns null

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;
    }
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM