Calling Non-Static Method In Static Method In Java [duplicate]
I'm getting an error when I try to call a non-static method in a static class.
Cannot make a static reference to the non-static method methodName() from the type playback
I can't make the method static as this gives me an error too.
This static method cannot hide the instance method from xInterface
Is there any way to get round calling an non-static method in another static method? (The two methods are in seperate packages and seperate classes).
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);
}
}
public class StaticMethod{
public static void main(String []args)throws Exception{
methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
the above code not executed because static method must have that class reference.
public class StaticMethod{
public static void main(String []args)throws Exception{
StaticMethod sm=new StaticMethod();
sm.methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
This will be definitely get executed. Because here we are creating reference which nothing but "sm" by using that reference of that class which is nothing
but (StaticMethod=new Static method()
) we are calling method one (sm.methodOne()
).
I hope this will be helpful.