簡體   English   中英

一類同名JAVA中的靜態和非靜態方法

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

我知道不可能在一個類中重寫一個方法。 但是,有沒有辦法使用非靜態方法作為靜態方法呢? 例如,我有一個加數字的方法。 我希望此方法在沒有對象的情況下有用。 是否可以在不創建其他方法的情況下執行類似的操作?

編輯:我的意思是,如果我將一個方法設為靜態,我將需要它接受參數,並且如果我創建了一個已經設置了變量的對象,那么再次對具有相同參數的對象調用函數將非常不舒服。

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

}

我知道代碼不正確,但是我想展示自己想做的事情。

我希望此方法在沒有對象的情況下有用。 是否可以在不創建其他方法的情況下執行類似的操作?

您將不得不創建另一個方法,但是您可以使非靜態方法調用靜態方法,這樣您就不會重復代碼,並且如果您以后想要更改邏輯,則只需在一個地方進行。

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

但是,有沒有辦法使用非靜態方法作為靜態方法呢?

不,不可能。

如果需要在靜態和非靜態上下文中使用此方法,請使其為static 但是,相反的配置是不可能的。

將其設置為靜態,然后可以與對象一起使用,也可以不使用它。

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

MyTest.add(); //prints hello

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM