calling non-static method in static method in Java

2018-12-31 03:02发布

This question already has an answer here:

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

14条回答
梦该遗忘
2楼-- · 2018-12-31 03:29

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.

查看更多
步步皆殇っ
3楼-- · 2018-12-31 03:30
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.

查看更多
登录 后发表回答