静态方法和非静态方法有什么区别? [英] What is the difference between a static method and a non-static method?

查看:31
本文介绍了静态方法和非静态方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看下面的代码片段:

代码 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 作为答案.

What is the difference between these code snippets? Both output 15 as an answer.

推荐答案

静态方法属于类本身,非静态(又名实例)方法属于从该类生成的每个对象.如果您的方法所做的事情不依赖于其类的个体特征,请将其设为静态(这将使程序的占用空间更小).否则,它应该是非静态的.

A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.

示例:

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().如果你用方法 2 尝试,它会失败.但这会起作用: Foo bar = new Foo(1);bar.method2();

You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();

这篇关于静态方法和非静态方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆