Static and non-static method in one class with the

2020-04-05 12:23发布

问题:

I know it is impossible to override a method in one class. But is there a way to use a non-static method as static? For example I have a method which is adding numbers. I want this method to be usefull with an object and also without it. Is it possible to do something like that without creating another method?

EDIT: What I mean is, if I make a method static I will need it to take arguments, and if I create an object with variables already set it will be very uncomfortable to call function on my object with same arguments again.

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

}

I know the code is incorrect but i wanted to show what I want to do.

回答1:

I want this method to be usefull with an object and also without it. Is it possible to do something like that without creating another method?

You will have to create another method, but you can make the non-static method call the static method, so that you do not duplicate the code and if you want to change the logic in the future you only need to do it in one place.

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


回答2:

But is there a way to use a non-static method as static?

No, it's not possible.

If you need this method to be used in static and non-static context, then make it static. The opposite configuration, however, is not possible.



回答3:

Make it static, then it can be used with object and without it.

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

MyTest.add(); //prints hello

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


标签: java static