Static Keyword:
1. The static keyword is applicable for the Class Members.
2. The static Class Members are accessed using Class Name.
3. Non static members are accessed using through reference variable or object.
4. The static members are loaded once into the memory for program execution.
5. The static members are shared across the objects.
6. Non-static & Static Class Members are inherited to the subclass
Static Program:
1234567891011121314151617181920212223242526272829
package org.totalqa.java; public class Student { int rollno=1; char section='A'; static String schoolName="ABC"; public static void main(String[] args) { Student s1 = new Student(); s1.rollno=2; s1.section='B'; System.out.println(s1.rollno); System.out.println(s1.section); Student s2= new Student(); System.out.println(s2.rollno); System.out.println(s2.section); System.out.println(Student.schoolName); //Can we call static class members using objects?? Yes System.out.println(s1.schoolName); s1.schoolName="DEF"; System.out.println(s2.schoolName); //can we call non-static using ClassName?? No //System.out.println(Student.rollno); }}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package org.totalqa.java; public class Student { int rollno=1; char section='A'; static String schoolName="ABC"; public static void main(String[] args) { Student s1 = new Student(); s1.rollno=2; s1.section='B'; System.out.println(s1.rollno); System.out.println(s1.section); Student s2= new Student(); System.out.println(s2.rollno); System.out.println(s2.section); System.out.println(Student.schoolName); //Can we call static class members using objects?? Yes System.out.println(s1.schoolName); s1.schoolName="DEF"; System.out.println(s2.schoolName); //can we call non-static using ClassName?? No //System.out.println(Student.rollno); } } |
2
B
1
A
ABC
ABC
DEF