-4

I have some doubts about access modifiers used for top level classes in Java.

1) Can access modifier public or default be used only with top level classes or even with nested classes?

2) Lets say there are two different classes A and B, both in different packages. Then in order to have access (acess to class members) to class A by class B , then both top level class, that is ‘A’ as well as class members should be defined public, right ? If either class or class members are not public then class B will not have access to class A, right ?

Please correct if I'm wrong.

Dev Choudhary
  • 105
  • 2
  • 8

1 Answers1

0

1) Nested classes can have the same access modifiers as top level classes.

2) In order to access class A from class B, only A needs to be public. Class B may be package private (default). B can only access methods of A if A's methods are public (if B does not inherit from A). If class A is package private, then it doesn't matter if A contains any public methods - they won't be accessible by B.

See also the Oracle docs and this stackoverflow thread.

Community
  • 1
  • 1
beosign
  • 433
  • 5
  • 10