What is the difference between Static and Not Static Methods
What is the difference between Static and Not Static Methods (Java)? Please provide examples.
Solution
Java static method : Applying static method to any method makes it a static method.
Features:
1)It belongs to class unlike other methods which belongs to objects of a class.
2)Since they belong to the class, there is no need to create an instance of a class to invoke these methods.
Invoking a static method : ClassName.methodName(args)
3)They are used to access only the static members of the class. It can not access non-static members.
4)Static methods cannot refer to \"this\" or \"super\" keywords.
5)Memory is allocated only once during class loading.
6) They are executed only once in the program.
eg1, one of the most common example of a static method is main method used in java program.
class Sample {
public static void main(String[] args) {
display();
}
static void display() {
System.out.println(\"This is a demo program\");
}
}
Output:
This is a demo program
eg2,
class Calculate{
static int area(int x){
return x*x;
}
public static void main(String args[]){
int res=Calculate.area(7);
System.out.println(res);
}
}
Output:
49
Non static methods : It belongs to each object that is generated from that class.
If your method does something that depend on the individual characteristics of its class, we declare it as a non static method.
Otherwise it should be static.
2) Memory is allocated multiple time whenever method is calling.
3) They are accessed using objects of a class.
Invoking a non static method : ObjectName.methodName(args)
4) They can be executed multiple times using different objects.
class Foo {
int age;
public Foo(int a) {
age = a;
}
public int getAge() {
return age;
}
public static void main(String args[]){
Foo ob=new Foo(24);
ob.getAge(); //Non static method called using object
}
}

