我知道在一个类中覆盖一个方法是不可能的.但有没有办法使用非静态方法作为静态?例如,我有一个添加数字的方法.我希望这个方法对一个对象有用,也没有它.是否可以在不创建其他方法的情况下执行此类操作?
编辑:我的意思是,如果我使一个方法静态,我将需要它来获取参数,如果我创建一个已经设置变量的对象,再次使用相同的参数调用我的对象上的函数会非常不舒服.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道代码不正确,但我想展示我想做的事情.
Hel*_*ira 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());
}
}
Run Code Online (Sandbox Code Playgroud)