Reputation: 8374
public class X {
public void close() {
// ...
}
public class XInputStream extends InputStream {
public void f() {
close(); // are we calling close() on InputStream or X??
}
}
}
The compiler is fine with this sort of thing, so obviously it knows which method to call. What exactly is the rule in the language spec for resolving this?
Other than renaming my close()
method, are there any steps I could take to make this code more readable?
Upvotes: 0
Views: 63
Reputation: 2238
Since you have an inner class:
public class XInputStream extends InputStream
the close() method that is called here is the one that is found in the InputStream class that you are extending from.
Also, you have to wrap the close() method with a try-catch, and any class that extends InputStream must either be declared abstract or implement the method read().
Upvotes: 0
Reputation: 44808
The relevant portion of the JLS is §6.4.1. Basically, the compiler will look in the smallest scope possible for the correct method. The first scope it checks is in XInputStream
. It finds a close
method, so it calls that one.
To make it more readable, you can qualify your method calls: this.close()
to call InputStream::close
or X.this.close()
to call X::close
.
Upvotes: 7