繁体   English   中英

一类同名JAVA中的静态和非静态方法

[英]Static and non-static method in one class with the same name JAVA

我知道不可能在一个类中重写一个方法。 但是,有没有办法使用非静态方法作为静态方法呢? 例如,我有一个加数字的方法。 我希望此方法在没有对象的情况下有用。 是否可以在不创建其他方法的情况下执行类似的操作?

编辑:我的意思是,如果我将一个方法设为静态,我将需要它接受参数,并且如果我创建了一个已经设置了变量的对象,那么再次对具有相同参数的对象调用函数将非常不舒服。

public class Test {

    private int a;
    private int b;
    private int c;

    public Test(int a,int b,int c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public static String count(int a1,int b1, int c1)
    {        
        String solution;
        solution = Integer.toString(a1+b1+c1);
        return solution;
    }


    public static void main(String[] args) {

       System.out.println(Test.count(1,2,3));
       Test t1 = new Test(1,2,3);
       t1.count();
    }

}

我知道代码不正确,但是我想展示自己想做的事情。

我希望此方法在没有对象的情况下有用。 是否可以在不创建其他方法的情况下执行类似的操作?

您将不得不创建另一个方法,但是您可以使非静态方法调用静态方法,这样您就不会重复代码,并且如果您以后想要更改逻辑,则只需在一个地方进行。

public class Test {
    private int a;
    private int b;
    private int c;

    public Test(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public String count() {
        return count(a, b, c);
    }

    public static String count(int a1, int b1, int c1) {
        String solution;
        solution = Integer.toString(a1 + b1 + c1);
        return solution;
    }

    public static void main(String[] args) {
        System.out.println(Test.count(1, 2, 3));
        Test t1 = new Test(1, 2, 3);
        System.out.println(t1.count());
    }
}

但是,有没有办法使用非静态方法作为静态方法呢?

不,不可能。

如果需要在静态和非静态上下文中使用此方法,请使其为static 但是,相反的配置是不可能的。

将其设置为静态,然后可以与对象一起使用,也可以不使用它。

 public class MyTest() {
     public static int add() {
         System.out.println("hello");
     }
 }

MyTest.add(); //prints hello

MyTest myobject = new MyTest();
myobject.add(); //prints hello

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM