Static Method vs Non- Static Method in Java
In Java, methods can be declared as either static or non-static, also known as instance methods. The main differences between static and non-static methods are as follows:
Static methods belong to the class, while non-static methods belong to instances of the class. This means that you can call a static method without creating an object of the class, but you need an object to call a non-static method.
Static methods can access only static variables and other static methods, whereas non-static methods can access both static and non-static variables and methods of the class.
Static methods are shared among all instances of the class, while non-static methods are specific to each instance of the class.
Static methods cannot be overridden in subclasses, while non-static methods can be overridden.
Here's an example to illustrate the difference between static and non-static methods:
javapublic class MyClass {
private static int staticVar;
private int instanceVar;
public static void staticMethod() {
// Can only access staticVar and other static methods
staticVar = 10;
}
public void instanceMethod() {
// Can access both staticVar and instanceVar, and other methods
staticVar = 5;
instanceVar = 3;
}
}
In the example above, the staticMethod()
is a static method and can be called like this: MyClass.staticMethod()
. The instanceMethod()
is a non-static method and needs to be called on an instance of the class: MyClass obj = new MyClass(); obj.instanceMethod();
.
In summary, use static methods when you don't need to access instance variables or methods and when you want to share a method among all instances of the class. Use non-static methods when you need to access instance variables or methods and when you want each instance to have its own copy of the method.
Comments
Post a Comment