English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Static members (methods/A variable (field) belongs to the class and it will be loaded into memory along with the class. You can call it without creating an object (use the class name as a reference). There is only one copy of a static field available throughout the class, that is, the value of a static field is the same for all objects. You can use the static keyword to define a static field.
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(); } }
Output Result
Value of num in the main method 50 Value of num in the demo method 50
If you want to refer to a class's own static member (within the same class), you do not need to refer to the class itself; you can directly access the static member.
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); } }
Output Result
Value of num in the demo method 50
In Java, you can include classes within classes, which are called inner classes.
public class Outer{ public class Inner{ } }
When you have a class within another class, it only acts as an instance member of the outer class. Therefore, if you declare an inner class as static, you can access its members (inner class) using its name-
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(); } }
Output Result
200 This is my nested class 200
If you try to reference a static inner class's (static) member, you do not need to use the name of the outer class and can reference the member using only the name of the inner class.
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(); } }
Output Result
200 This is my nested class 200