2

I realized inner classes can be declared as public. What are practical use cases of public inner classes and how are they different than inner classes declared without public keyword?

public class OuterClass{
    class InnerClass{

    }
}

public class OuterClass{
    public class InnerClass{

    }
}
nmd_07
  • 616
  • 1
  • 8
  • 21
  • 2
    The difference is that if it's public you can use it from another package. Same as public means on any class. – khelwood Sep 14 '20 at 19:05
  • See [What is the difference between "public class" and just "class"?](https://stackoverflow.com/q/16779245/3890632) – khelwood Sep 14 '20 at 19:12
  • As for a use case, I suppose it could be used as a organization tool (though having it as separate files under a package would be better). For example, if you want to have a bunch of Shape objects then you could make them nested under a Shape class to call `Shape.Square`, `Shape.Circle`, ect. Typically a nested class would be private and tightly connected to the parent class such as a Node class inside a List class. – Tim Hunter Sep 14 '20 at 19:12
  • I confess that, even after 20+ years of Java programming, this still surprised me. I never knew that an inner class could be public. I guess I didn't know because I never came across a real use for such a thing, and I still can't think of a real-world application, with all due respect to @TimHunter. – Kevin Boone Sep 14 '20 at 19:48
  • @KevinBoone No, I agree. There are far better tools for organization purposes, that's just the only ill-advised but still potentially usable scenario I can think of for a public inner. – Tim Hunter Sep 14 '20 at 19:56

1 Answers1

1

The difference is when passing an instance through a method/constructor.

Here is some code to show what I mean.

Class com.test.OutterClass.

package com.test;

public class OutterClass {

    // public class
    public class InnerClass {

    }
    
    // not public class
    class InnerClass1 {

    }
}

Class com.test2.TestClass

package com.test2;

public class TestClass {


     // Works, because OutterClass.InnerClass is public.
     TestClass(OutterClass.InnerClass t) {
     
    }

    // Doesn't work because OutterClass.InnerClass1 is not public.
    TestClass(OutterClass.InnerClass1 t) {
    
    }

}
hms11
  • 54
  • 5