Static in Java

作者: _浅墨_ | 来源:发表于2023-03-27 20:47 被阅读0次

In Java, the static keyword is used to create class-level variables and methods.

When a variable or method is declared as static, it means that it belongs to the class itself, rather than to any particular instance of the class. This means that there is only one copy of the variable or method, regardless of how many instances of the class are created.

To declare a variable or method as static, simply include the keyword before the variable or method declaration. For example:

public class MyClass {
    static int myStaticVariable = 42;
    static void myStaticMethod() {
        System.out.println("Hello, world!");
    }
}

In this example, myStaticVariable and myStaticMethod are both declared as static. This means that they can be accessed using the class name, rather than an instance of the class:

int x = MyClass.myStaticVariable;
MyClass.myStaticMethod();

Note that static variables and methods cannot access non-static variables or methods directly. If you need to access a non-static variable or method from a static context, you will need to create an instance of the class first.

来自 Cursor 的解答,讲得非常明白了。
公元2023,AI 元年。

相关文章

  • 2019-03-06 Java Interface

    Java static static 特点 static是一个修饰符,用于修饰成员。 static修饰的成员被所有...

  • 2019-03-07 Java static

    Java static static 特点 static是一个修饰符,用于修饰成员。 static修饰的成员被所有...

  • Test

    ```java public static void test() {} ```

  • 无标题文章

    ```java public static void main() { ```

  • 我的乌龟流星雨

    import java.awt.*; public class java{ public static void ...

  • Java 面向对象2

    Java 面向对象 1. static 和 final static关键字---修饰成员变量 用static修饰的...

  • 1.3 static 关键字

    static 关键字 《Java编程思想》 中:static方法就是没有this的方法 static 修饰的方法或...

  • Java static

    Static variable In this above example, we have created an...

  • Java static

    在总结完 想知道Java代码执行顺序么,Let's go 一文后,对 Java 中的static关键字有了更深的理...

  • Java static

    参考http://www.cnblogs.com/chenssy/p/3386721.html http://de...

网友评论

    本文标题:Static in Java

    本文链接:https://www.haomeiwen.com/subject/tegzrdtx.html