Mar
03
2009
Java: Instantiate an innerclass from the main constructor does not works.
Posted by Kristof in USA
public class Main
{
public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.getInt());
}
public class Test
{
public Test()
{
}
public int getInt()
{
return 5;
}
}
}
While it works in C#:
class Program
{
static void Main(string[] args)
{
Test t = new Test();
Console.WriteLine(t.GetInt());
Console.ReadLine();
}
public class Test
{
public Test()
{
}
public int GetInt()
{
return 5;
}
}
}
If you move the class in Java to a seperate file it (obviously) works. But why? No idea.

Entries (RSS)
The problem is that Java and C# handle their inner classes differently. Java inner classes have access to the members of the enclosing class. Thus you cannot construct the Main.Test class without having an instance of Main, and as you are in a static function you have no such reference, and this is what the error: “non-static variable this cannot be referenced from a static context” is telling you.
Test t = new Test() can be rewritten as Test t = this.new Test()
I hope this makes things clear.
@Jan no that does not work, (I tried it), and it actually makes sense, there is no ‘this’ variable in a static context.
So we’re still looking for a solution over here
Well the solution is to make it a static inner class so like this
public class Main {
public static class Test {
}
}
but then Test cannot access Main’s variables anymore.
Hey,
Dit is een pure gok he, dus schiet me nie dood, geen programmas meer om het te testen :
public class Main
{
public static void main(String[] args)
{
Test t = this.new Test();
System.out.println(t.getInt());
}
private class Test
{
public Test()
{
}
public int getInt()
{
return 5;
}
}
}