milo milo - 1 month ago 15
Java Question

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

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.

Answer

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