类中的“静态"关键字有什么作用?

What does the #39;static#39; 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();
    }
}

但它给出了错误

无法访问静态方法 main 中的非静态字段

Cannot access non-static field in static method main

所以我把clock的声明改成这样:

So I changed the declaration of clock to this:

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?

推荐答案

static 成员属于类而不是特定实例.

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

这意味着 static 字段只有一个实例存在[1],即使您创建了该类的一百万个实例,或者您不要创建任何.它将被所有实例共享.

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. It will be shared by all instances.

由于static 方法也不属于特定的实例,它们不能引用实例成员.在给出的示例中,main 不知道应该引用 Hello 类的哪个实例(因此也不知道 Clock 类的哪个实例).static 成员只能引用 static 成员.实例成员当然可以访问 static 成员.

Since static methods also do not belong to a specific instance, they can't refer to instance members. 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. static members can only refer to static members. Instance members can, of course access static members.

旁注:当然,static成员可以通过对象引用访问实例成员.

Side note: Of course, static members can access instance members through an object reference.

例子:

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]:根据运行时特性,它可以是每个 ClassLoader 或 AppDomain 或线程一个,但这不是重点.

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

这篇关于类中的“静态"关键字有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:类中的“静态"关键字有什么作用?

基础教程推荐