This is possible in Java:
package x;
public class X {
// How can this method be public??
public Y getY() {
return new Y();
}
}
class Y {}
So what's a good reason the Java compiler lets me declare the getY()
method as public
? What's bothering me is: the class Y
is package private, but the accessor getY()
declares it in its method signature. But outside of the x
package, I can only assign the method's results to Object
:
// OK
Object o = new X().getY();
// Not OK:
Y y = new X().getY();
OK. Now I can somehow try to make up an example where this could somehow be explained with method result covariance. But to make things worse, I can also do this:
package x;
public class X {
public Y getY(Y result) {
return result;
}
}
class Y {}
Now I could never call getY(Y result)
from outside of the x
package. Why can I do that? Why does the compiler let me declare a method in a way that I cannot call it?
Why does the compiler let me do something that leads to unusable methods
? There I'll update the question like that... – Kussell