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.

4 Responses to “Java: Instantiate an innerclass from the main constructor does not works.”
  1. Jan says:

    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.

  2. Kristof says:

    @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 :)

  3. Jan says:

    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.

  4. Michael says:

    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;
    }
    }
    }

  5.  
Leave a Reply


And shepherds we shall be, for thee my Lord for thee, power hath descended forth from thy hand, that our feet may swiftly carry out thy command. We shall flow a river forth to thee, and teeming with souls shall it ever be. In nomine Patris, et Filii, et Spiritus Sancti.