Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access modifiers for inner classes [duplicate]

Tags:

java

Possible Duplicate:
protected/public Inner Classes

I am sure the question has been asked already, but I wasn't able to find one so I'll ask...

I am curious what is the difference between private(protected) and public inner class. I am able to use both from out of the containing class using the outer class object.

public class A{
   private class B{

   }

   public static void main(String[] args){
     A a = new A();
     B b = a.new B();
   }
}
like image 458
Headshota Avatar asked Aug 08 '11 20:08

Headshota


2 Answers

A private inner class can still be accessed within the class that defined it.

If you have another class, B isn't visible:

public class C {
   public static void main(String[] args){
     A a = new A();
     B b = new B(); // compile error
   }
}
like image 164
Jeremy Avatar answered Oct 05 '22 20:10

Jeremy


Actually, you are inside class A still, since the main method is a static method of class A

like image 38
Zak Avatar answered Oct 05 '22 20:10

Zak