Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

java - “ static”关键字在课程中做什么?(What does the 'static' keyword do in a class?)

To be specific, I was trying this code:

(具体来说,我正在尝试以下代码:)

package hello;

public class Hello {

    Clock clock = new Clock();

    public static void main(String args[]) {
        clock.sayTime();
    }
}

But it gave the error

(但是它给了错误)

Cannot access non-static field in static method main

(无法在静态方法main中访问非静态字段)

So I changed the declaration of clock to this:

(因此,我将clock的声明更改为:)

static Clock clock = new Clock();

And it worked.

(而且有效。)

What does it mean to put that keyword before the declaration?

(将关键字放在声明之前是什么意思?)

What exactly will it do and/or restrict in terms of what can be done to that object?

(就可以对对象执行的操作而言,它将确切地执行和/或限制什么?)

  ask by Click Upvote translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

static members belong to the class instead of a specific instance.

(static成员属于该类,而不是特定的实例。)

It means that only one instance of a static field exists) [1] even if you create a million instances of the class or you don't create any.

(这意味着,即使您创建了该类的一百万个实例,也没有创建任何static实例) ,但仅存在一个static字段实例) [1] 。)

It will be shared by all instances.

(它将被所有实例共享。)

Since static methods also do not belong to a specific instance, they can't refer to instance members.

(由于static方法也不属于特定实例,因此它们不能引用实例成员。)

In the example given, main does not know which instance of the Hello class (and therefore which instance of the Clock class) it should refer to.

(在给出的示例中, main不知道应引用Hello类的哪个实例(以及Clock类的哪个实例)。)

static members can only refer to static members.

(static成员只能引用static成员。)

Instance members can, of course access static members.

(实例成员当然可以访问static成员。)

Side note: Of course, static members can access instance members through an object reference) . 旁注:当然, static成员可以通过对象引用)访问实例成员。)

Example:

(例:)

public class Example {
    private static boolean staticField;
    private boolean instanceField;
    public static void main(String[] args) {
        // a static method can access static fields
        staticField = true;

        // a static method can access instance fields through an object reference
        Example instance = new Example();
        instance.instanceField = true;
    }

[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.

([1]:根据运行时的特性,每个ClassLoader或AppDomain或线程可以是一个,但是那不是重点。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...