Calling Non-Static Method In Static Method In Java
To call a non-static method from a static method in Java, you need to create an instance of the class and call the non-static method on that instance.
Here is an example of how you can call a non-static method from a static method in Java:
public class MyClass {
public void nonStaticMethod() {
// non-static method code
}
public static void staticMethod() {
MyClass instance = new MyClass(); // create instance of the class
instance.nonStaticMethod(); // call non-static method on the instance
}
}
In this example, the nonStaticMethod()
method is a non-static method and the staticMethod()
method is a static method. The staticMethod()
method creates an instance of the MyClass
class and calls the nonStaticMethod()
method on that instance.
Keep in mind that a static method belongs to the class and is not tied to a specific instance of the class. A non-static method, on the other hand, belongs to an instance of the class and can access the instance variables and methods of the class.
I hope this helps! Let me know if you have any questions.