I have to instantiate an object of an inner class and it works fine for me inside the class but not outside.
// Fichero Main.java
public class Main {
public static void main( String[] args )
{
Test.Interior interior = new Test.Interior(); // Esta línea falla
Test.InteriorStatic interiorStatic = new Test.InteriorStatic();
}
}
// Fichero Test.java
public class Test {
public class Interior {
}
public static class InteriorStatic {
}
public void algo()
{
Test.Interior interior = new Test.Interior();
}
}
The line in which I indicate that it fails gives the following compilation error:
Main.java:15: error: an enclosing instance that contains Test.Interior is required
But exactly the same line within algo()
itself works fine. And as much Test
as they Test.Interior
are public
.
If I make the class Test.Interior
is static
it does not give the error, but it is a class that I have no possibility to modify in the production code.
Interior
it is an inner class ( inner class , JLS, §8.1.3 ). To create an instance of the inner class, you must first create an instance of the outer class. Or more accurately, you must first create the "immediately enclosing instance" ( immediately enclosing instance , JLS, §15.9.2 ). That is:by creating the nested class, you are indicating that the instances of Interior depend on Test. that's why you must first create an instance of Test, and then create the inner instances.