How to Call a Non Static Method From a Static Method in Java

In Java programming, "methods" are functions within classes used to define the functionality of objects created from classes. "Static" methods are methods that the class defines apart from objects. Static methods work as independent functions contained within a class. The difference is that you need an instance of a class object in order to call a non-static method, while for static methods you only need to call the class itself. In order to call a non-static method -- which requires an object -- from a static method, you need to have an instance of an object within the static method.

Things You'll Need

  • Java Development Kit
  • Text editor
Show More

Instructions

    • 1

      Declare a class with a static method:

      class testing{

      public static void static_method(){
      }
      }

    • 2

      Declare an instance of a class inside this class. For example, in class "testing," the method "static_method" is static, meaning it can only be called through the class -- with the syntax "testing.static_method()." In order to call a non-static method, create an object, of class "A" in this example, inside the static method to call the non-static method:

      public static void static_method(){

      A new_object_A = new A();

      }

    • 3

      Call the non-static method of "A" from the static method "static_method" in the testing class:

      public static void static_method(){

      A new_object_a = new A();
      A.non_static_method();
      }

Related Searches:

References

Comments

Related Ads

Featured