static keyword in java
The "static"
keyword can be applied to an inner class (a class defined within another class), method or field (a member variable of a class).
Static
methods and variables are shared among all instances of a class. They can be invoked and accessed without creating new instances of the class.
Example
- public class Student{
- String name;
- String id;
- static String college;
- static void displayCollege() {
- System.out.println("College name is "+college);
- }
- void displayStudentDetails() {
- System.out.println("Name is "+name+" id is "+id);
- }
- }
public class Student{ String name; String id; static String college; static void displayCollege() { System.out.println("College name is "+college); } void displayStudentDetails() { System.out.println("Name is "+name+" id is "+id); } }
The static
members can be accessed using class name directly, We don’t need to create an object for the same.
static variable college and static method displayCollege() can be accessed as below
- Student.college="Oxford";
- Student.displayCollege();
Student.college="Oxford"; Student.displayCollege();
whereas the non static method displayStudentDetails() can be called using an object of Student class as below
- Student student = new Student();
- student.name="John";
- student.id="1234";
- student.displayStudentDetails();
Student student = new Student(); student.name="John"; student.id="1234"; student.displayStudentDetails();
The outer class cannot be static, only inner class can be static as shown below
- public class Library{
- static class Book{
- }
- }
public class Library{ static class Book{ } }
The inner class Book can be instantiated without creating an instance of the enclosing class Library.
Example
- Library.Book book = new Library.Book();
Library.Book book = new Library.Book();