3

I have a main class "m" and 2 inner classes called sub1,sub2, where sub2 is static class:

public class m
{
  String n="n";
  static String s="s";
  public class sub1
  {
    public void fn(){System.out.println(n);}
    //static public void fs(){System.out.println(s);}
  }
  static class sub2
  {
    //public void fn(){System.out.println(n);}
    static public void fs(){System.out.println(s);}
  }
  public void f()
  {
    sub1 s1=new sub1();//OK, no error
    sub2 s2=new sub2();//OK
  }

  public static void main(String[] args)
  {
    m obj=new m();
    sub1 s1=new sub1();//Error
    s1.fn();
    //s1.fs();
    sub2 s2=new sub2();//OK
    //s2.fn();
    s2.fs();
  }
}

I compile it under linux using Openjdk, it reports error

$ java -version
openjdk version "1.8.0_91"
OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-3ubuntu1~16.04.1-b14)
OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)

$ javac m.java 
m.java:24: Error: Cannot reference non-static variable this in a static context.
    sub1 s1=new sub1();//Error
            ^
1 Errors

This is weird to me: 1. In m.f() member function, we can "sub1 s1=new sub1();", but in main, we cann't 2. staic class sub2 can have instance,while non-static sub1 cann't?

Is this a design of Java? Why?

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119

1 Answers1

7
  • Non static Inner classes are treated as members of outer class.
  • To create their instances, you need to use reference of outer class.

So you have to do something like this,

OuterClass outer = new OuterClass();
InnerClass inner = outer.new InnerClass();

So, in your case,

m obj = new m();
sub1 s1 = obj.new Sub1();
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
  • "Inner classes are treated as member variables of outer class." What does this mean? Inner classes are not member variables of outer classes. In what way are they "treated" as such? – Erwin Bolwidt Oct 21 '16 at 06:53
  • Maybe a bit confusing words I wrote. I mean to say they act as members of outer class and hence they need to be accessed using outer class reference. I have studied this from kathie sierra book for SCJP, 8th Chapter on inner classes. – Prasad Kharkar Oct 21 '16 at 06:57
  • "Non static Inner classes are treated as members of outer class." that's true but static member classes are *also* members of the outer class. JLS: "A member class is a class whose declaration is directly enclosed in another class or interface declaration." The only thing special about inner classes is that they have an enclosing instance. – Erwin Bolwidt Oct 21 '16 at 10:10