小编典典

Java 静态方法和非静态方法有什么区别?

java

请参见下面的代码段:

代码1

public class A {
    static int add(int i, int j) {
        return(i + j);
    }
}

public class B extends A {
    public static void main(String args[]) {
        short s = 9;
        System.out.println(add(s, 6));
    }
}

代码2

public class A {
    int add(int i, int j) {
        return(i + j);
    }
}

public class B extends A {
    public static void main(String args[]) {
    A a = new A();
        short s = 9;
        System.out.println(a.add(s, 6));
    }
}

这些代码段之间有什么区别?两者都15作为答案输出。


阅读 1106

收藏
2020-02-28

共1个答案

小编典典

静态方法属于类本身,而非静态(aka实例)方法属于从该类生成的每个对象。如果你的方法执行的操作不依赖于其类的单个特征,请将其设置为静态(这将使程序的占用空间减小)。否则,它应该是非静态的。

例:

class Foo {
    int i;

    public Foo(int i) { 
       this.i = i;
    }

    public static String method1() {
       return "An example string that doesn't depend on i (an instance variable)";
    }

    public int method2() {
       return this.i + 1; // Depends on i
    }
}

你可以像这样调用静态方法:Foo.method1()。如果你使用method2尝试该操作,它将失败。但这将起作用:Foo bar = new Foo(1); bar.method2();

2020-02-28