From what I understand, usually the static method should be called using class's reference or it can be called directly without reference if its in a static method or static block.
But does this apply when static method is called from child class static blocks?
Why it allows such thing, as static methods are not inherited, it should only be allowed using parent class name right?
public abstract class abs {
/**
* @param args
*/
abstract void m();
static void n(){
System.out.println("satic method");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
class myclass extends abs{
@Override
void m() {
// TODO Auto-generated method stub
}
static{
n();
}
}
Why my child class static block can call parent class static method without reference or classname?
Static method n() is inherited by subclass myclass, so you can call it directly in the static block of myclass.
Usually the static method should be called using class's reference or it can be called directly without reference if its in a static method or static block.
Not really. For example an instance method can invoke a static method without prefixing the class.
More generally, static members (fields as methods) have to be invoked by prefixing their class only as the compiler cannot infer the class where they belong to.
As you invoke a static method defined in the parent class from a subclass (and static methods are inherited in the subclasses), you don't need to prefix the class of the method invocation as the compiler infer that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With