Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a public method return a private type?

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();
    }
}
like image 904
Monstieur Avatar asked Sep 25 '14 11:09

Monstieur


People also ask

Can public methods access private methods?

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.

Can a private method call a public method?

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.

Can private method return value in Java?

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.

Can methods be made private?

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.


1 Answers

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.

like image 75
Duncan Jones Avatar answered Sep 28 '22 04:09

Duncan Jones