This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Lift to ask:staticWhat role do keywords play in a class?

When I test the following code:

package hello;

public class Hello {

    Clock clock = new Clock();

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

The following error was reported

Cannot access non-static field in static method main
Copy the code

So I changed the clock declaration to something like this:

static Clock clock = new Clock();
Copy the code

Now that the code runs successfully, what’s the point of prefacing the declaration with a keyword? What does it do to the object?

Answer a

Basic usage of static members

public class Hello
{
    // value / method
    public static String staticValue;
    public String nonStaticValue;
}

class A
{
    Hello hello = new Hello();
    hello.staticValue = "abc";
    hello.nonStaticValue = "xyz";
}

class B
{
    Hello hello2 = new Hello(); // here staticValue = "abc"
    hello2.staticValue; // will have value of "abc"
    hello2.nonStaticValue; // will have value of null
}
Copy the code

This is how values are shared across all instances of a class without having to create an instance to get the value.

Hello hello = new Hello();
hello.staticValue = "abc";
Copy the code

You can call static values directly using the class name

Hello.staticValue = "abc";
Copy the code

Answer two

Static is a non-access control modifier that belongs to a class rather than an instance of a class.

This means that all instances share a static variable, even if there are a million instances. Because static methods do not enter an instance, they cannot call non-static methods either. Static members can only reference static members. Instance members can access static members.

Note: Static members can also access instance members using objects

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;
    }
Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/4…