Calling Non-Static Method In Static Method In Java [duplicate]
Asked Answered
V

14

144

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).

Vanguard answered 11/1, 2010 at 15:38 Comment(0)
I
173

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.

Iveson answered 11/1, 2010 at 15:40 Comment(0)
D
110

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

new Foo().nonStaticMethod();
Defloration answered 11/1, 2010 at 15:40 Comment(1)
@EJP For security purposes, and this is what I do with my project, in the case of dependency injection, it is useful to only have initialization code be instantiated for initialization, and not at the arbitrary discretion of code using my API. Thus, when an initialization cycle happens, the temporary object containing only constants and non-static methods which are dynamically initialized through dependency injection can be safely loaded and discarded as needed. The purpose of static methods is more like the purpose of "pure" functions such as in functional programming languages.Avent
B
73

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);
    }
}
Buoy answered 12/6, 2012 at 8:14 Comment(0)
M
14
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.

Mutule answered 25/11, 2015 at 6:2 Comment(0)
E
7

You need an instance of the class containing the non static method.

Is like when you try to invoke the non-static method startsWith of class String without an instance:

 String.startsWith("Hello");

What you need is to have an instance and then invoke the non-static method:

 String greeting = new String("Hello World");
 greeting.startsWith("Hello"); // returns true 

So you need to create and instance to invoke it.

Emera answered 11/1, 2010 at 15:45 Comment(0)
L
7

It sounds like the method really should be static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.

However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")

So as long as the method is present in xInterface, and your class implements xInterface, you won't be able to make the method static.

If you can't change the interface (or don't want to), there are several things you can do:

  • Make the class a singleton: make the constructor private, and have a static data member in the class to hold the only existing instance. This way you'll be invoking the method on an instance, but at least you won't be creating new instances each time you need to call the method.
  • Implement 2 methods in your class: an instance method (as defined in xInterface), and a static method. The instance method will consist of a single line that delegates to the static method.
Lucania answered 11/1, 2010 at 16:9 Comment(1)
A very advanced answer! Thank you!Assemble
F
4

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.

class A
{
    void method()
    {
    }
}
class Demo
{
    static void method2()
    {
        A a=new A();

        a.method();
    }
    /*
    void method3()
    {
        A a=new A();
        a.method();
    }
    */

    public static void main(String args[])
    {
        A a=new A();
        /*an instance of the class is created to access non-static method from a static method */
        a.method();

        method2();

        /*method3();it will show error non-static method can not be  accessed from a static method*/
    }
}
Furfural answered 27/1, 2015 at 18:8 Comment(1)
thanks, approach is clearer, help me lot ! sometimes, lower reputation guys' are helpful for this way.Grandmother
W
1

There are two ways:

  1. Call the non-static method from an instance within the static method. See fabien's answer for an oneliner sample... although I would strongly recommend against it. With his example he creates an instance of the class and only uses it for one method, only to have it dispose of it later. I don't recommend it because it treats an instance like a static function.
  2. Change the static method to a non-static.
Wesleyanism answered 11/1, 2010 at 15:40 Comment(0)
E
1

You can't get around this restriction directly, no. But there may be some reasonable things you can do in your particular case.

For example, you could just "new up" an instance of your class in the static method, then call the non-static method.

But you might get even better suggestions if you post your class(es) -- or a slimmed-down version of them.

Expellant answered 11/1, 2010 at 15:42 Comment(0)
D
1

The easiest way to use a non-static method/field within a a static method or vice versa is...

(To work this there must be at least one instance of this class)

This type of situation is very common in android app development eg:- An Activity has at-least one instance.

public class ParentClass{

private static ParentClass mParentInstance = null;

ParentClass(){
  mParentInstance = ParentClass.this;           
}


void instanceMethod1(){
}


static void staticMethod1(){        
    mParentInstance.instanceMethod1();
}


public static class InnerClass{
      void  innerClassMethod1(){
          mParentInstance.staticMethod1();
          mParentInstance.instanceMethod1();
      }
   }
}

Note:- This cannot be used as a builder method like this one.....

String.valueOf(100);
Decrement answered 1/9, 2014 at 14:34 Comment(0)
M
1

I use an interface and create an anonymous instance of it like so:

AppEntryPoint.java

public interface AppEntryPoint
{
    public void entryMethod();
}

Main.java

public class Main
{
    public static AppEntryPoint entryPoint;

    public static void main(String[] args)
    {
        entryPoint = new AppEntryPoint()
        {

            //You now have an environment to run your app from

            @Override
            public void entryMethod()
            {
                //Do something...
                System.out.println("Hello World!");
            }
        }

        entryPoint.entryMethod();
    }

    public static AppEntryPoint getApplicationEntryPoint()
    {
        return entryPoint;
    }
}

Not as elegant as creating an instance of that class and calling its own method, but accomplishes the same thing, essentially. Just another way to do it.

Mitchelmitchell answered 16/10, 2015 at 21:16 Comment(0)
P
1

It is not possible to call non-static method within static method. The logic behind it is we do not create an object to instantiate static method, but we must create an object to instantiate non-static method. So non-static method will not get object for its instantiation inside static method, thus making it incapable for being instantiated.

Pskov answered 2/5, 2017 at 6:43 Comment(2)
It is possible, if you have an instance to call the non-statc method on. It could be provided as a parameter, for example, or be a static data member of the class.Butterflies
Actually as per my understanding, calling non static method with instance is beyond the scope of this question.Pskov
T
0

Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.

Though answered 9/10, 2013 at 23:11 Comment(1)
The question isn't about constructors.Butterflies
D
0

You can call a non static method within a static one using: Classname.class.method()

Decimal answered 30/12, 2014 at 11:53 Comment(2)
adding .class between the class and method did work thanksAkene
No you can't. This is just fantasy, unless the method you want to call is defined injava.lang.Class.Butterflies

© 2022 - 2024 — McMap. All rights reserved.