Reputation: 65
Consider the following program:
public class A
{
public static void main(String[] args)
{
class B
{
private B()
{
System.out.println("local");
}
}
// how are we able to create the object of the class having private constructor
// of this class.
B b1= new B();
System.out.println("main");
}
}
Output: local main
A class having private constructor means we can create object inside the class only, but here am able to create instance outside the class. can someone explain how are we able to create the object of B outside class B??
Upvotes: 3
Views: 1899
Reputation: 49372
Refer the JLS 6.6.1:
Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
The way this is implemented is using synthetic package-protected methods.
"If you like to hide the private members of your inner class, you may define an Interface with the public members and create an anonymous inner class that implements this interface. Refer to this code:"
class ABC{
private interface MyInterface{
public void printInt();
}
private static MyInterface mMember = new MyInterface(){
private int x=10;
public void printInt(){
System.out.println(String.valueOf(x));
}
};
public static void main(String... args){
System.out.println("Hello :: "+mMember.x); ///not allowed
mMember.printInt(); // allowed
}
}
Upvotes: 1
Reputation: 18986
You said that
A class having private constructor means we can create object inside the class only
But
Thats happened because you define your inner Class
in main(String[] args) method
Not in Top Level Class
If you try that
public class A {
class B {
private B() {
System.out.println("local");
}
}
public static void main(String[] args) {
B b1 = new B(); // you cant create object of inner Class B
System.out.println("main");
}
}
Then you cant create object of inner Class B
Upvotes: 0
Reputation: 9599
Because a Top Level Class
is a happy family, everyone can access one another despite private
.
6.6.1. Determining Accessibility
- A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
- Otherwise, if the member or constructor is declared
private
, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
Upvotes: 4
Reputation: 1616
You're allowed to even access private variables of that class too (try it!).
This is because you are defining that class inside the same class your calling it from, so you have private/internal knowledge of that class.
If you move Class B outside of Class A, it will work as expected.
Upvotes: 1