Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

static

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.

like image 603
milo Avatar asked Aug 03 '15 13:08

milo


2 Answers

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());
    }
}
like image 132
Helder Pereira Avatar answered Sep 22 '22 10:09

Helder Pereira


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.

like image 25
Konstantin Yovkov Avatar answered Sep 22 '22 10:09

Konstantin Yovkov