What is the role of the keyword static in the class?

Asked 2 years ago, Updated 2 years ago, 133 views

package hello;

public class Hello {

    Clock clock = new Clock();

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

When there was a code like this

Cannot access non-static field in static method main There's an error like this.

That's why static Clock clock = new Clock(); It's working well because I changed it like this. What's the difference between static and not static?

oop java static restriction language-feature

2022-09-22 13:21

1 Answers

A static member belongs to the class itself, not to a specific object. I mean, static is the idea that there's only one thing in every object, so if there's a million instances, all instances share one static member.

Also, the static method does not belong to a specific object, so you cannot refer to an instance member. So static members are only referenced in static methods. Instance methods can refer to static members.

public class Example {
    private static boolean staticField;
    private boolean instanceField;
    public static void main(String[] args) {
        //static methods can refer to static members.  
        staticField = true;

        // The static method can access the instance member when it is objectized.
        Example instance = new Example();
        instance.instanceField = true;
    }


2022-09-22 13:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.