Calling Non-Static Method In Static Method In Java


Answer :

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.


You could create an instance of the class you want to call the method on, e.g.

new Foo().nonStaticMethod(); 

Firstly create a class Instance and call the non-static method using that instance. e.g,

class demo {      public static void main(String args[]) {         demo d = new demo();         d.add(10,20);     // to call the non-static method     }      public void add(int x ,int y) {         int a = x;         int b = y;         int c = a + b;         System.out.println("addition" + c);     } } 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable