Java中静态方法中调用非静态方法

发布于 2024-08-17 15:13:03 字数 248 浏览 9 评论 0原文

当我尝试在静态类中调用非静态方法时出现错误。

无法从类型播放中静态引用非静态方法 methodName()

我无法将该方法设为静态,因为这也会给我带来错误。

此静态方法无法从 xInterface 隐藏实例方法

有没有办法绕过在另一个静态方法中调用非静态方法? (这两种方法位于单独的包和单独的类中)。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

恏ㄋ傷疤忘ㄋ疼 2024-08-24 15:13:03

从静态方法调用非静态方法的唯一方法是拥有包含非静态方法的类的实例。根据定义,非静态方法是在某个类的实例上调用的方法,而静态方法属于该类本身。

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.

分開簡單 2024-08-24 15:13:03

您可以创建要调用该方法的类的实例,例如

new Foo().nonStaticMethod();

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

new Foo().nonStaticMethod();
软的没边 2024-08-24 15:13:03

首先创建一个类实例并使用该实例调用非静态方法。
例如,

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);
    }
}

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);
    }
}
风吹过旳痕迹 2024-08-24 15:13:03
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;
    }
}

上面的代码没有执行,因为静态方法必须具有该类引用。

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;
    }
}

这肯定会被执行的。因为在这里我们通过使用该类的引用来创建除了“sm”之外什么都没有的引用
但是 (StaticMethod=new Static method()) 我们正在调用方法一 (sm.methodOne())。

我希望这会有所帮助。

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.

爱的故事 2024-08-24 15:13:03

您需要包含非静态方法的类的实例。

就像当您尝试在没有实例的情况下调用类 String 的非静态方法 startsWith 时:

 String.startsWith("Hello");

您需要的是拥有一个实例,然后调用非静态方法:

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

所以你需要创建实例来调用它。

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.

无名指的心愿 2024-08-24 15:13:03

听起来该方法实际上应该是静态的(即它不访问任何数据成员,并且不需要调用实例)。由于您使用了术语“静态类”,我知道整个类可能专用于可能是静态的类似实用程序的方法。

但是,Java 不允许接口定义方法的实现是静态的。因此,当您(自然地)尝试使该方法成为静态时,您会收到“无法隐藏实例方法”错误。 (Java 语言规范在 第 9.4 节中提到了这一点: “请注意,接口中声明的方法一定不能声明为静态,否则会发生编译时错误,因为静态方法不能是抽象的。”

因此只要该方法存在于xInterface,并且您的类实现了 xInterface,您将无法将该方法设为静态。

如果您无法更改接口(或不想更改),您可以执行以下操作:

  • 将类设为单例:将构造函数设为私有,并在类中使用静态数据成员来保存唯一现有的实例。这样,您将在实例上调用该方法,但至少您不会在每次需要调用该方法时创建新实例。
  • 在您的类中实现 2 个方法:一个实例方法(如 xInterface 中定义)和一个静态方法。实例方法将由委托给静态方法的一行组成。

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.
雨后咖啡店 2024-08-24 15:13:03

从静态方法调用非静态方法的唯一方法是拥有包含非静态方法的类的实例。

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*/
    }
}

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*/
    }
}
庆幸我还是我 2024-08-24 15:13:03

有两种方法:

  1. 从静态方法内的实例调用非静态方法。请参阅 fabien 对 oneliner 示例的回答...尽管我强烈建议不要这样做。在他的示例中,他创建了该类的一个实例,并且仅将其用于一种方法,只是稍后将其处理掉。我不推荐它,因为它将实例视为静态函数。
  2. 将静态方法更改为非静态方法。

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.
小巷里的女流氓 2024-08-24 15:13:03

你不能直接绕过这个限制,不。但根据您的具体情况,您可能可以采取一些合理的措施。

例如,您可以在静态方法中“新建”类的实例,然后调用非静态方法。

但是,如果您发布您的课程或它们的精简版本,您可能会得到更好的建议。

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.

書生途 2024-08-24 15:13:03

在静态方法中使用非静态方法/字段的最简单方法,反之亦然是...

(要实现这一点,必须至少有一个此类的实例)

这种情况在 Android 应用程序开发中非常常见,例如:- 一项活动至少有一个实例。

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();
      }
   }
}

注意:- 这不能用作像这样的构建器方法......

String.valueOf(100);

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);
烟花肆意 2024-08-24 15:13:03

我使用一个接口并创建它的匿名实例,如下所示:

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;
    }
}

不像创建该类的实例并调用其自己的方法那么优雅,但本质上完成了相同的事情。只是另一种方式来做到这一点。

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.

绝不放开 2024-08-24 15:13:03

静态方法中不能调用非静态方法。其背后的逻辑是我们不创建一个对象来实例化静态方法,但我们必须创建一个对象来实例化非静态方法。因此,非静态方法不会在静态方法内部实例化时获取对象,从而使其无法被实例化。

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.

眼藏柔 2024-08-24 15:13:03

构造函数是一种特殊的方法,理论上它是任何静态方法调用的“唯一”非静态方法。否则是不允许的。

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

柳若烟 2024-08-24 15:13:03

您可以使用以下方法在静态方法中调用非静态方法:
类名.class.method()

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文