I'm trying to call a method from another class with a console application. The class I try to call isn't static.
class Program
{
static void Main(string[] args)
{
Program p = new Program();
var myString = p.NonStaticMethod();
}
public string NonStaticMethod()
{
return MyNewClass.MyStringMethod(); //Cannot call non static method
}
}
class MyNewClass
{
public string MyStringMethod()
{
return "method called";
}
}
I get the error:
Cannot access non-static method "MyStringMethod" in a static context.
This works if I move the MyStringMethod to the class program. How could I succeed in doing this? I cannot make the class static nor the method.
To call a non-static variable from a static method, an instance of the class has to be created first. In this example, the integer a is not static. So to access it from the static method main, an instance of the class Calc has to be created.
But when we try to call Non static function i.e, TestMethod() inside static function it gives an error - “An object refernce is required for non-static field, member or Property 'Program. TestMethod()”. So we need to create an instance of the class to call the non-static method.
To call a non-static method from main in Java, you first need to create an instance of the class, post which we can call using objectName. methodName().
We can call non-static method from static method by creating instance of class belongs to method, eg) main() method is also static method and we can call non-static method from main() method . Even private methods can be called from static methods with class instance.
Just like you create an instance of the Program class to call the NonStaticMethod, you must create an instance of MyNewClass:
public string NonStaticMethod()
{
var instance = new MyNewClass();
return instance.MyStringMethod(); //Can call non static method
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With