non-static variable this cannot be referenced from a static context

I am mostly a C++ person and I haven't done any Java for several years. Below is a small example to illustrate the problem I am having. All the forums I have searched suggest that the code is correct. This problem is doing my head in and I can't use any of the classes I have created for my real application. Please do not suggest that I make my classes static because it is no use to me whatsoever. Java is 1.5.0_07 on SuSe 10.1

public class test2{

public class test{

int count;

test(){

count=0;

}

public void increment(){

count++;

}

}

public static void main(String args[]) {

test t=new test();

t.increment();

}

}

[714 byte] By [graham128a] at [2007-10-3 11:32:52]
# 1
Since test is an inner class in test2, try this:test2.test t = new test2.test();By the way, class names should start with upper case letters.
CaptainMorgan08a at 2007-7-15 13:59:43 > top of Java-index,Java Essentials,New To Java...
# 2

A nested needs to be - nested - in an instance of the embedding classpublic class Test2{

public class Test{

int count;

Test(){count=0;}

public void increment(){++count;}

}

public static void main(String args[]) {

Test t = new Test2().new Test();

t.increment();

}

}

tschodta at 2007-7-15 13:59:43 > top of Java-index,Java Essentials,New To Java...
# 3

Please do not suggest that I make my classes static because it is no use to me whatsoever.

It doesn't sound like you're aware that inner classes are associated with the state of the containing class instances unless you specifically declare them as static.

If you make "test" a normal class in its own right it will behave as you seem to expect.

Oh, and please capitalize the first letter of class names.

dcmintera at 2007-7-15 13:59:43 > top of Java-index,Java Essentials,New To Java...
# 4
"By the way, class names should start with upper case letters." Yes, I do know! This was a quickly hammered out example. tchodt: Many thanks for a complete and working explanation.
graham128a at 2007-7-15 13:59:43 > top of Java-index,Java Essentials,New To Java...