Your code does not work because you are trying to access a non-static member of A
(the nested class B
) from a static method (static main
); and you can only access non-static members of a class from a class instance.
So for your code to work, you have 3 options:
Instantiate B
from an instance of A
:
public class A{
private class B{
public B(){
System.out.println("class B");
}
}
public static void main(String[] args){
A a = new A();
B b = a.new B(); // instância de B a partir de uma instância de A
}
}
Change the method main
for non-static, because if it is an instance method, it has access to non-static members of its class:
public class A{
private class B{
public B(){
System.out.println("class B");
}
}
// instância de B a partir de um método não estático de A
public void doSomething(String[] args){
// A a = new A();
B b = new B();
}
}
Or declare B
as a static class, so it is accessible from static members (in this case, the method main
).
public class A{
// B declarado como classe estática
private static class B{
public B(){
System.out.println("class B");
}
}
public static void main(String[] args){
A a = new A();
B b = new B();
}
}
Update: In the second example, I changed the name of the method so that it would not be confused as an input method for a Java main class, as it would need to be static. This code has only the didactic role on nested classes.
Hello rogger, welcome to [en.so], could you give us more details? For example, which error occurs? In which line?
– Caputo
On the line I try to instantiate the Inner class B, the following error occurs: No enclosing instance of type A is accessible.
– rogger
Class B and private, so can only be instantiated from an instance of class A.
– Lucas Virgili
@Lucasvirgili In fact it is not because it is "private", it is for
B
be a member ofA
; even thoughB
was not private, this code would only work ifmain
were not static.– Caffé