Here is the key point on static
- static is a keyword in Java
- static variable also know as class variable.
- static variable are belong to class instead object.
let take look on code
public class Employee{
static int noOfEmployee;
}
In above "noOfEmployee" are the static variable or class variable.Class contain only one copy of this attribute even if you create thousand object.
- static method only access static attribute instead instance variable.
- We can access static variable by class name rather than object just like Math.PI
- We cannot refer static variable to this keyword
Let's take another look of code
public class Employee{
private static int noOfEmployee;
public int getNoOfEmployee(){
return noOfEmployee();
}
}
//////////////////////////////////////////////////////////
Another most usable code and static example is
public class Employee{
private static int noOfEmployee;
public static void main(){
Thread.sleep(1000);
System.out.println(noOfEmployee);
}
}
In above sleep is a static method of Thread class and see static method accept only static variable.
Whether instance method can contain static method.
Here is difference between the instance and class method by code
No comments:
Post a Comment