How to use private class in Java?

In Java, private classes can only be used within the class that defines them, and cannot be directly accessed by other classes. Private classes are typically used to encapsulate internal implementation details or provide auxiliary functionality.

“Here is an example:” -> “This is an example:”

public class OuterClass {
    private class PrivateClass {
        public void doSomething() {
            System.out.println("PrivateClass is doing something.");
        }
    }
    
    public void accessPrivateClass() {
        PrivateClass privateObj = new PrivateClass();
        privateObj.doSomething();
    }
}

In the example above, OuterClass defines a private class called PrivateClass. The method accessPrivateClass() is a public method of OuterClass that can access and use the private class PrivateClass. Other classes cannot directly access PrivateClass.

To use the private class, just create an instance of OuterClass and call the public method accessPrivateClass().

public class MainClass {
    public static void main(String[] args) {
        OuterClass outerObj = new OuterClass();
        outerObj.accessPrivateClass();
    }
}

If you run the above code, it will output:

PrivateClass is doing something.

Note: Private classes can only be used within the class where they are defined, making it impossible to directly access or create instances of private classes in other classes.

bannerAds