What is static keyword?
The static keyword denotes that a member variable or method, can be accessed without instantiation of the class to which it belongs. In simple term, it means that you can call a method, even if you've never created the object of a class to which it belongs.
The static keywords can be variables or methods.
The static keyword denotes that a member variable or method, can be accessed without instantiation of the class to which it belongs. In simple term, it means that you can call a method, even if you've never created the object of a class to which it belongs.
The static keywords can be variables or methods.
- Static variables
- Static methods
- Class (Not Nested)
- Constructor
- Interfaces
- Instance Variables
- Local Variables
- When a variable is declared with the keyword static, its called a class variable. All instances share the same copy of the variable.
- A class variable can be accessed directly with the class, without the need to create a instance.
- The static variable can be used to refer the common property of all objects (that is unique for each object) e.g. company name of employees,college name of students etc.
- The static variable gets memory only once in class area at the time of class loading.
1 2 3 4 5 | class TestClass { int rollno; String name; static String college = "COEM"; // Static variable } |
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //Program of static variable class Student { int rollno; String name; static String college = "COEM"; Student(int r, String n) { rollno = r; name = n; } void display() { System.out.println(rollno + " " + name + " " + college); } public static void main(String args[]) { Student s1 = new Student(111, "John"); Student s2 = new Student(222, "Jerry"); s1.display(); s2.display(); } } |
Output:
111 John COEM
222 Jerry COEM
2) static method
- It is a method which belongs to the class and not to the object(instance).
- A static method can access only static data and can change the value of it. It can not access non-static data (instance variables).
- A static method can be accessed directly without creation of an object.
1 2 3 4 5 6 7 8 9 10 | class Addition { static int add(int x, int y) { return x + y; } public static void main(String args[]) { int result = Addition.add(5, 5); System.out.println(result); } } |
The above add() method which is declared as static can be invoke without creating an object of class Addition.
It was so nice article. Thank you for valuable information
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDelete