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 an instance of the class.
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 main
method to non-static, since if it is an instance method, you have access to non-static members of your 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 static class, so it is accessible from static members (in this case, the main
method).
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 method name to not be confused as input method of a Java main class, because to do so it would need to be static. This code has only the didactic role on nested classes.