OOPS in JAVA 8
static keyword
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
variable (also known as class variable).
method (also known as class method).
block.
nested class.
static variable
If you declare any variable as static, it is known static variable.
1. The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
2. The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
NOTE : Java static property is shared to all objects.
Example: Program of counter by static variable.
class Counter{ static int count=0;//will get memory only once and retain its value Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } Output: 1 2 3
Static variable vs Instance Variable
Static variable | Instance Variable |
Represent common property. | Instance Variable. |
Accessed using class name. | Accessed using object. |
get memory only once. | get new memory each time a new object is created. |
Static Method
If you apply static keyword with any method, it is known as static method.
1. A static method belongs to the class rather than object of a class.
2. A static method can be invoked without the need for creating an instance of a class (or objects).
3. static method can access static data member and can change the value of it.
Example: Program to get cube of a given number by static method.
class Calculate{ static int cube(int x){ return x*x*x; } public static void main(String args[]){ int result=Calculate.cube(5); System.out.println(result); } } Output: 125
Restrictions for static method
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class A{ int a=40; //non static public static void main(String args[]){ System.out.println(a); } } Output: Compile Time Error
Q. Why java main method is static??
Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.
static Block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
class S2{ static{System.out.println("static block is invoked");} public static void main(String args[]){ System.out.println("main method is invoked"); } } Output: static block is invoked main method is invoked
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )