0

main function is part of the class therefore we should be able to access root as it is instead of tree.root after creating an object of the class, as instance variables are accessed using this variable inside instance method?

class Main
{ 

    Node root; 
    Main() 
    { 
        root = null; 
    } 

    public static void main(String[] args) 
    { 
        Main tree = new Main(); 

      //  tree.root = new Node(1); 
        } 
} ```
  • Do you know the difference between static and instance members of a class? – Kayaman Sep 04 '19 at 10:21
  • You should read up on 'static' vs 'instance'. In the main method, there is no instance of Main, so there is no root to be accessed. the main method can have several instances of the Main class, so which root should it take? – Stultuske Sep 04 '19 at 10:21
  • try to add in constroctore Main( Node root=null) { this.root = root; } – Mohammed Al-Reai Sep 04 '19 at 10:25
  • @Mohammed_Alreai how would that change anything? the root element would still have to be called from the instance of Main – Stultuske Sep 04 '19 at 10:27

1 Answers1

1

You cannot access the non static class field from the static method no matter if it's main or another one - you need a reference to the object to know at what exactly root you are pointing, or you need a static field

The static method can be called even if no Main object was created yet - which root variable would you like to access in such situation?

m.antkowicz
  • 13,268
  • 18
  • 37