I'm a little bit confuse. While reading java tutorial a question "wake up" for me. If i decided that the nested class need to be with private access modifier, does it matter (at all) if the nested class will be static or not? Initially i thought it doesn't matter but after writing some classes in order to verify my intuition i found some different "results" when running the program with and without the "static" keyword.
Following code doesn't compile, get the following compilation error: "non static method callByInnerClass() cannot be referenced from a static context"
public class Outer
{
private String outerString = "nnnn";
private InnerStatic iS;
public void createInnerClassInstance()
{
iS = new InnerStatic("innter");
}
public void runInnerMethod()
{
iS.callInnerMethod();
}
// if method runs it mean the inner static class can run outer methods
public String calledByInnerClass()
{
System.out.println("Inner class can call Outer class non static method");
System.out.println("nn value after ruuning inner class is: " +outerString );
}
public static class InnerStatic
{
public String innerString;
public InnerStatic(String str)
{
innerString = str;
}
public void callInnerMethod()
{
System.out.println(innerString);
outerString = "aaa";
calledByInnerClass();
}
}
}
When removing "static" keyword before inner class, then program is compiled successfully. What is the reason that when "static" keyword exist, than the nested class can't find his outer class instance (and considered inner)? I read that when creating from different class an object of inner class, then inner class automatically has outer class instance, but this situation feels a little bit different