English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
静态成员(方法/变量)属于该类,它将与该类一起加载到内存中。您可以在不创建对象的情况下调用它。(使用类名作为参考)。在整个类中只有一个静态字段的副本可用,即,静态字段的值在所有对象中都相同。您可以使用static关键字定义一个静态字段。
public class Sample{ static int num = 50; public static void demo(){ System.out.println("Value of num in the demo method ")+ Sample.num); } } public class Demo{ public static void main(String args[]){ System.out.println("Value of num in the main method ")+ Sample.num); Sample.demo(); } }
출력 결과
Value of num in the main method 50 demo 메서드에서 num의 값 50
如果要引用一个类本身的静态成员(在同一类中),则无需引用该类,则可以直接访问静态成员。
public class Sample{ static int num = 50; public static void demo(){ System.out.println("Value of num in the demo method ")+ Sample.num); } public static void main(String args[]){ demo(); System.out.println(num); } }
출력 결과
demo 메서드에서 num의 값 50
Java에서는 클래스 내에 클래스를 포함할 수 있으며, 이러한 클래스는 내부 클래스라고 합니다.
public class Outer{ public class Inner{ } }
다른 클래스 내에 클래스를 가지고 있을 때, 그것은 외부 클래스의 인스턴스 멤버로서만 동작합니다. 따라서 내부 클래스를 정적으로 선언하면 그 이름만으로도 그 멤버(내부 클래스)에 접근할 수 있습니다.-
outer_class_name.inner_class_name.members
class OuterDemo { static int data = 200; static class InnerDemo { public static void my_method() { System.out.println("This is my nested class"); System.out.println(OuterDemo.data); } } } public class StaticClassExample{ public static void main(String args[]) { System.out.println(OuterDemo.data); //nested Outer.InnerDemo = new Outer.InnerDemo(); OuterDemo.InnerDemo.my_method(); } }
출력 결과
200 This is my nested class 200
하나의 클래스 내에 클래스를 가지고 있을 때, 그것은 외부 클래스의 인스턴스 멤버로서만 동작합니다. 따라서 내부 클래스를 정적으로 선언하면 그 이름만으로도 그 멤버(내부 클래스)에 접근할 수 있습니다.
class OuterDemo { static int data = 200; static class InnerDemo { public static void my_method() { System.out.println("This is my nested class"); System.out.println(OuterDemo.data); } } public static void main(String args[]) { System.out.println(data); InnerDemo.my_method(); } }
출력 결과
200 This is my nested class 200