-1

I have seen the responses given in Why doesn't Java allow overriding of static methods? and acknowledge that it would only be useful in specific situations...

So can we override a static method in java?

Community
  • 1
  • 1
HedonicHedgehog
  • 592
  • 1
  • 6
  • 17

1 Answers1

1

In Java, you can't override a static method directly (and in most cases it wouldn't make sense, for static methods the call signature is (Class.method()).

Instead of overriding the method directly, you can create a new static method in your other class and call that directly (NewClass.method())

public class Employee{
   public static double calculateNewSalary(double salary){
       return salary*1.03; //give a yearly increase
   }
}

public class SpecialEmployee extends Employee{
   public static double calculateNewSalary(double salary){
      return Employee.calculateSalary(salary) * 1.02; //give them an additional raise
   }
}

Now in your main method you will call SpecialEmployee.calculateNewSalary(double) instead of Employee.calculateNewSalary(double).

However, although this method allows your base methods to be more generic, it reduces code maintainability because this is uncommon code practice and your logic is now split across multiple classes. Keep in mind that you can do the same thing by simply creating a more customize-able or overloaded base method:

public class Employee{
   public static double calculateNewSalary(double salary){
       return salary*1.03; //give a yearly increase
   }
   public static double calculateNewSalary(double salary, double additionalIncrease){
       return salary*1.03*additionalIncrease; 
   }
}

or simply create one customizable method:

   public static double calculateNewSalary(double salary, double additionalIncrease){
       if(additionalIncrease == null){
         return salary * 1.03;
       }
       return salary*1.03*additionalIncrease; //give a yearly increase
   }
HedonicHedgehog
  • 592
  • 1
  • 6
  • 17
  • 1
    `additionalIncrease == null`? Primitives can't be null. In any case, what problem does this solve? What does this have to do with overriding? The question makes little sense and the answer makes even less. – shmosel Mar 20 '17 at 18:19
  • 1
    as you noted, you aren't really overriding anything, but creating additional static methods of the same name. imho its kind of like taking aim at your foot. eventually someone on the project is going to get lazy and forget to fully qualify `TheClass.methodName()` and just use `methodName()` .. it will compile just fine (with a few warnings) but now the code contains logic errors that will be difficult to trace. – trooper Mar 20 '17 at 18:28
  • This is called `Hiding` – boxed__l Mar 20 '17 at 18:46