-4

Say we have this:

class Foo {}
public class Bar{}

versus:

public class Bar{
  public class Foo{}
}

I can't figure out the difference. In both cases, Foo should be private to the file that contains Bar. Is there a difference? Of course, if we make it static, then it might be available to other files?

public class Bar{
  public static class Foo{}
}

but I am specifically asking about the situation without the static keyword.

Naman
  • 27,789
  • 26
  • 218
  • 353
  • 1
    *In both cases, Foo should be private to the file that contains Bar.* Wrong in both cases. – shmosel Feb 12 '19 at 04:32
  • 1
    what do you mean *Foo should be private to the file that contains Bar* ? More likely a duplicate of https://stackoverflow.com/questions/11398122/what-are-the-purposes-of-inner-classes – Naman Feb 12 '19 at 04:33
  • Well please correct me, maybe it should be package private, not private to the file –  Feb 12 '19 at 05:37

1 Answers1

0

From the Oracle documentation,

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Please refer this Official Documentation for more details about the nested class.

https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

  • 1
    This not the 'official documentation'. That consists of the JLS, JVM Spec., and the Javadoc. This is a tutorial. And it is about nested classes, not inner classes specifically. – user207421 Feb 12 '19 at 04:50
  • Is inner Class not a type of Nested class ? I believe, the example classes mentioned in the Question are Nested class and the 'tutorial' / 'document' answers the question. ( usage of private, public, static references in the nested class ) – Sivaraj Velayutham Feb 12 '19 at 05:13
  • @SivarajVelayutham The OP explicitly stated that they were only asking about inner classes (_"I am specifically asking about the situation without the static keyword"_), so linking to documentation discussing nested classes in general was inappropriate. – skomisa Feb 16 '19 at 04:37