Sobes.tech
Junior — Middle

Is it possible to implement a public method that returns an object of a private inner class within this class?

sobes.tech AI

Answer from AI

Yes, in Java, it is possible to implement a public method in a class that returns an object of a private inner class. The inner class can be declared as private, but since it is inside the outer class, the outer class is allowed to create and return its instances.

Example:

public class Outer {
    private class Inner {
        void sayHello() {
            System.out.println("Hello from Inner");
        }
    }

    public Inner getInner() {
        return new Inner();
    }
}

In this example, the getInner() method is public and returns an object of the private inner class Inner. However, outside the Outer class, the type Inner will be inaccessible, so the returned object can only be used within Outer or through interfaces/abstractions.

Is it possible to implement a public method that… - sobes.tech