Why is it possible to return a private
nested class from a public
method in a public
class? Shouldn't the compiler complain about the return type's visibility being less than the method?
public final class Outer {
private static final class Configurator {
private Configurator() {
}
}
public static Configurator configure() {
return new Configurator();
}
}
An object user can use the public methods, but can't directly access private instance variables. You can make methods private too. Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.
If a private method must call a public method, then the content of the public method should be taken and placed in a private method, which both methods can then call.
they are both supposed to return int values. The private method is the one that does all the work and the public is the one that is called from the main program.
Private methods are typically used when several methods need to do the exact same work as part of their responsibility (like notifying external observers that the object has changed), or when a method is split in smaller steps for readability.
You can call such a method from outside the class, but only if you are happy to throw away the result.
public class TestClass {
public static void main(String[] args) throws Exception {
Outer.configure(); // this is valid
}
}
or if you are happy to refer to the result as an Object
:
public class TestClass {
public static void main(String[] args) throws Exception {
Object o = Outer.configure(); // this is valid
}
}
The compiler allows this because it doesn't break any rules of Java. Object
is simply the only publicly available superclass of your private class.
I doubt there are many practical uses for this pattern. If you wish to return an opaque object, that's better done by passing back a public class with no public methods, since you can at least type-check it when passed back into classes that need to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With