Static keyword in java
Static is a keyword as well as modifier, and it can use before member function , data member,block and nested class.
When we use this modifier with any class/data/method behavior modified.
In java there is not access modifier nor access specifier just only modifier.
Static can’t be use before any class or constructor not before any local variable.
Example:
Class Student{
String name,collegeName;
int rollNo;
StudentSelect(String nam,String college,int roll){
name=nam;
collegeName= college;
rollNo= roll;
}
void showInfo() {
System.out.println(name);
System.out.println(collegeName);
System.out.println(rollNo);
}
public static void main(String args[]) {
Student s1= new Student(“Ankit”,”nitw”,157905);
}
}
Syntax to access Non-static datamember and method
- Object.NS DataM or NS DataF(same class as well as other class).
- ObjectReference . NS DataM or NS DataF(same class as well as other class Standard Approach).
- And NS DataM or NS DataF can directly call in constructor in same class and in another non static method.
- Class name.StaticDataMember or SMF(same class as well as other class Standard Approach).
Difference between non-static and static data member
Static Data Member
- Static data member represents the properties of class.
- Memory allocated in class area at class loading time and this memory shared by multiple objects it means in case of static data member the single copy created in the memory.
- Standard approach to call static data Member using class name
Non-Static Data Member
- its represent the properties of object.
- memory is allocated for each objects separately in the heap area at the time of object creation
- standard approach to call non static datamember with object Reference.