静态和非静态方法在一个具有相同名称JAVA的类中

时间:2015-08-03 13:37:04

标签: java static

我知道在一个类中覆盖一个方法是不可能的。但有没有办法使用非静态方法作为静态?例如,我有一个添加数字的方法。我希望这个方法对一个对象有用,也没有它。是否有可能在不创建其他方法的情况下做同样的事情?

编辑: 我的意思是,如果我创建一个静态方法,我将需要它来获取参数,如果我创建一个已设置变量的对象,那么再次使用相同的参数调用我的对象上的函数会非常不舒服。

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

}

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

3 个答案:

答案 0 :(得分:10)

  

我希望这个方法对一个对象有用,也没有它。   是否可以在不创建另一个的情况下做类似的事情   方法

你必须创建另一个方法,但你可以让非静态方法调用静态方法,这样你就不会复制代码,如果你想在将来改变逻辑,你只需要这样做在一个地方。

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

答案 1 :(得分:6)

  

但有没有办法将非静态方法用作静态?

不,这是不可能的。

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

答案 2 :(得分:0)

使其静止,然后它可以与对象一起使用,没有它。

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

MyTest.add(); //prints hello

MyTest myobject = new MyTest();
myobject.add(); //prints hello
相关问题