4

I can create an object in the main method and call the other method with the object I created.

public class Obj{

    public static void main(String[] args) {

    Obj obj = new Obj();
    obj.yourNameIs();

    }

    void yourNameIs(){
    System.out.println("TY");
    }
}

However, i have to change yourNameIs method to static if I want to call it without creating an object.

public class Obj{

    public static void main(String[] args) {

    yourNameIs();

    }

    static void yourNameIs(){
    System.out.println("TY");
    }
}

I understand you cannot call a non-static method in a static method in this case the main method. But why I can create an object in the main method and then I can call a non-static method such as yourNameIs()? I mean why I do not need to change yourNameIs() to static method?

OPK
  • 4,120
  • 6
  • 36
  • 66

2 Answers2

2

If you create an instance of a class, you can call any instance (i.e. non static) method for this isntance. It doesn't matter if the instance is created in a static method.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

A non-static method is associated with an instance of the class. Once you have an instance, you can call such methods from anywhere you like (subject to Java's visibility rules). The fact that main() is static makes no difference at all here.

NPE
  • 486,780
  • 108
  • 951
  • 1,012