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?
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?
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
}