What is difference between protected static
method and protected
method? For example demo
and demo2
in Data2
respectively
Data.java:
package pack1;
import pack2.*;
public class Data extends Data2 {
public static void main(String args[]){
System.out.println("From main class");
Data d=new Data();
d.first();
}
void first(){
Data2 d2=new Data2();
d2.demo();
d2.demo2();
}
}
Data2.java:
package pack2;
public class Data2 {
protected static void demo(){
System.out.println("In method demo");
}
protected void demo2(){
System.out.println("In method demo2");
}
}
1
A static method is a method which doesn’t belong to a particular instance of a class. It belongs to the class itself.
You could write Demo2.demo()
to call the static method directly on the class without creating an instance. But you couldn’t call Demo2.demo2()
because demo2 isn’t static and thus can only be called on an instance you created with the new
keyword.
Because a static method is not (necessarily) bound to a specific instance of a class, it can only access static variables (the value of static variables is shared between all instances of a class while the value of a non-static variable is different for each instance you create with the new
keyword).
You might wonder “what’s the reason for a static protected method, considering that it’s impossible to call it from anywhere except from an instance of that class?”. Usually there isn’t much reason to declare a private or protected method as static. Static methods are usually public. But when the behavior of a method does not affect or is affected by the state of the current instance, declaring it static can be a way to document this fact.
3