0

Here is my code.

 package com.company;

 public class P194Constructor1
 {
   class Number
   {
    int num;

    public Number()
    {
        num=10;
        System.out.println("생산자 호출!");
    }
    public int getNumber()
    {
        return num;
    }
  }

  static class Constructor1
  {
    public static void main(String[] args)
    {
        Number num1=new Number();
        System.out.println(num1.getNumber());
        Number num2=new Number();
        System.out.println(num2.getNumber());
    }
  }
}

Why do I get 'non-static variable this cannot be referenced from a static context'? (in this code)

Here is the error message.

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

Why even here?

  static class Constructor1
  {
    public static void main(String[] args)
    {
        Number num1=new Number();
        System.out.println(num1.getNumber());
        Number num2=new Number();
        System.out.println(num2.getNumber());
    }
  }

Thank you.

azro
  • 53,056
  • 7
  • 34
  • 70
  • 1
    You should never have a main method inside of a nested class for one – Hovercraft Full Of Eels Jan 20 '18 at 15:58
  • `class Number` is inner class. That means its instance can only be created via *outer class instances* like `Outer o = new Outer(); Inner i = o.new Inner();`. In case of non-static methods of outer class we can access outer instance which invoked that method via `this` keyword which allows us to write code like `Inner i = this.new Inner()` but since compiler can add `this.` for us we can also write `Inner i = new Inner()` (but only in non-static methods where `this` exist, in case of `static` methods there is no `this` because method is run on class itself). – Pshemo Jan 20 '18 at 16:02
  • You should probably make Number a static class – OneCricketeer Jan 20 '18 at 16:03

0 Answers0