main() is a static method and is part of class. Then how is it that main can access instance members?

Recommended Answers

All 6 Replies

Static methods can not directly access any instance variables or methods but they can access them by using their object reference.
Static methods may even access private instance variables via a object reference.
All private instance variables are private to its class, they can be accessed by static methods or non-static method of the class.

how is it that main can access instance members?

Do you have an example where that is done? Please post it.

Here's an example:

public class MyClass {
   // member variable can't be accessed directly in static method
   private String name;

   public static void main(String[] args) {
      // create an object to access its member variables
      MyClass test = new MyClass();
      test.name = "any name";
      // ... do some other stuff
   }
}

That example is how every and any method in any class would do it.

although most would perfer the use of mutators instead of directly trying to access (private) instance variables

That is the getters and the setters methods.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.