Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java doesn't allow to create instance of inner class? [duplicate]

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?

like image 409
Hind Forsum Avatar asked Jul 28 '26 22:07

Hind Forsum


1 Answers

  • 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();
like image 171
Prasad Kharkar Avatar answered Jul 31 '26 13:07

Prasad Kharkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!