Is it necessary to set inner class as private?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Is it necessary to set inner class as private??

I'm seeing no difference! can some one explain why?

11th May 2017, 12:20 PM
Hari Shankar C B
Hari Shankar C B - avatar
5 Answers
+ 4
If it is not private you are ABLE to access, like this: OuterClass.InnerClass innerObject = outerObject.new InnerClass();
11th May 2017, 1:19 PM
Felipe Cruz
Felipe Cruz - avatar
+ 3
It's not necessary. If you want reach outside from the class you can referenced it Class.InnerClass.
11th May 2017, 12:42 PM
Szabó Gábor
Szabó Gábor - avatar
+ 2
@Hari I made a demo code for it: https://code.sololearn.com/c226EEgRU7U6/#java
11th May 2017, 1:19 PM
Szabó Gábor
Szabó Gábor - avatar
+ 1
Creating an inner class is simple, you just need to write a class within a class. A class cannot be associated with the access modifier private. Unlike a class, an inner class CAN be private and once you declare an inner class private, it cannot be accessed from an object outside the class. - It is a way of logically grouping classes that are only used in one place; - It increases encapsulation; - It can lead to more readable and maintainable code.
11th May 2017, 12:48 PM
Felipe Cruz
Felipe Cruz - avatar
0
even if it is not private I'm not able to access it!! can we access the inner class from main? @gabor
11th May 2017, 1:02 PM
Hari Shankar C B
Hari Shankar C B - avatar