Posts: 266
Threads: 239
Joined: Apr 2011
What is the difference between Static method and the method we write in Class definition?
Why Static method can not be called using Object of a class?
Posts: 9,583
Threads: 8,089
Joined: Apr 2011
The instance variables and methods belong to an object of a class whereas static data members and methods are associated with class and are not tied to any object. There will be only single copy of static data member inside a class. The static data members are shared by all the objects of class. The static methods can not only be accessed by class but by the objects of a class. The non-staic variable and methods cannot be accessed within static method.
// See the example below
class Employee{
private static int count = 0; //staic variable
public Employee(){
count++ ;
}
// static method
public static void get()
{
System.out.println("The value of count: " + count);
}
} // end of Employee class
// driver class
public class Example {
public static void main(String[] args){
Employee.get(); // calling static method using class
Employee e1 = new Employee();
e1.get() ; // calling static method using an object of class
Employee e2 = new Employee();
e2.get() ; // calling static method using an object of class
} // end of main
} // end of class