-1
import java.util.*;
public class MyClass {
    MyClass()
    {
    }
    
    public static void main(String args[]) {
       
        Node n = new Node();// CT error - non-static variable this cannot be referenced from a static context
        
         MyClass obj = new MyClass();//works (Why? Since this is also a non-static)
        test t = new test();//works (Why? Since this is also a non-static)
        
    }
    
    class Node{
    };
    
}

class test{
}

How can main method (which is static) call it's own class' constructor even if it is non-static? And can't call nested class' constructor.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    Don't nest classes. Or if you must do this, put static on the inner class You accidentally made an inner class that needs an outer instance to work. You're misunderstanding the error. – Nathan Hughes Jan 11 '22 at 01:40

1 Answers1

0

It's important to note the distinction between calling a static method, which you can do whenever, and calling a non-static method, which must be done on an instance.

class Foo {

    public void run() {
        System.out.println("Hello, world!");
    }

    public static void static_run() {
        Foo f = new Foo();
        f.run();
    }

    public static void main(String[] args) {
        Foo.static_run();  // Calling a static method from a static context
        (new Foo()).run();  // Calling a non-static method on an instance of Foo
        Foo.run();  // Error! Cannot call a non-static method from a static context
        A a = new Foo.A(); // This is fine since A is a static class
        B b1 = new Foo.B();  // Error! B is non-static but is being called from a static context
        B b2 = new (new Foo()).B(); // This is fine since B is created on an instance of Foo, not from a static context
        C c = new C(); // This is fine since top-level classes are implicitly static (i.e. they must be static)
    }  

    static class A {}
    class B {}
}

class C {}

Notice how we can create instances of our class within it's own static methods.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
  • @NewProgrammer I wouldn't say all top-level classes are static. Simply that the static vs non-static distinction makes no sense for top-level classes. To say that something is non-static means that it belongs to an instance of its enclosing class, and to say that it's static means that it does not. If there's no enclosing class, then something can neither be static nor non-static. – Dawood ibn Kareem Jan 11 '22 at 05:09