Java: Instantiate an innerclass from the main constructor does not works.

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 thoughts on “Java: Instantiate an innerclass from the main constructor does not works.

  1. 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. @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. 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. 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;
    }
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>