Can the static methods be override?

No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods. But we can declare static method with the same signature in the subclass and it is not consider override it is method hiding concept. 

public class OverrideSuper {

    public static void hello() {
        System.out.println("In super class method");
    }
   
}

class OverrideSubClass extends OverrideSuper
{
    @Override
    public static void hello() {
// The method hello() of type OverrideSubClass must override or
// implement a supertype method
        System.out.println("In sub-class method");
    }
   
}

In above code we have override the hello() method in sub-class then complier giving compile time error hence static method overriding not possible
In below code we have declare same name static method mean we are hiding the method here.

 class OverrideSuper {

    public static void hello() {
        System.out.println("In super class method");
    }
   
}

public class OverrideSubClass extends OverrideSuper
{
    public static void hello() {
        System.out.println("In sub-class method");
    }
   
    public static void main(String[] args) {
        hello();
    }
   
}

// In sub-class method
 

The above code is method hiding concept in java

No comments:

Post a Comment