我知道不可能重写一个类中的方法。但是有没有办法将非静态方法用作静态方法呢?例如,我有一个将数字相加的方法。我希望这个方法对于有对象和没有对象都有用。是否可以在不创建其他方法的情况下执行类似的操作?
编辑: 我的意思是,如果我将一个方法设置为静态,我将需要它接受参数,如果我创建一个已经设置了变量的对象,那么再次使用相同的参数在我的对象上调用函数将会非常不舒服。
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 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?
您将必须创建另一个方法,但您可以使非静态方法调用静态方法,这样您就不会重复代码,并且如果将来要更改逻辑,您只需在一处进行即可。
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());
}
}
关于java - JAVA同名类中的静态和非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40960905/