Why doesn't Java allow overriding of static methods?

后端 未结 22 2724
谎友^
谎友^ 2020-11-21 05:49

Why is it not possible to override static methods?

If possible, please use an example.

22条回答
  •  心在旅途
    2020-11-21 06:21

    A Static method, variable, block or nested class belongs to the entire class rather than an object.

    A Method in Java is used to expose the behaviour of an Object / Class. Here, as the method is static (i.e, static method is used to represent the behaviour of a class only.) changing/ overriding the behaviour of entire class will violate the phenomenon of one of the fundamental pillar of Object oriented programming i.e, high cohesion. (remember a constructor is a special kind of method in Java.)

    High Cohesion - One class should have only one role. For example: A car class should produce only car objects and not bike, trucks, planes etc. But the Car class may have some features(behaviour) that belongs to itself only.

    Therefore, while designing the java programming language. The language designers thought to allow developers to keep some behaviours of a class to itself only by making a method static in nature.


    The below piece code tries to override the static method, but will not encounter any compilation error.

    public class Vehicle {
    static int VIN;
    
    public static int getVehileNumber() {
        return VIN;
    }}
    
    class Car extends Vehicle {
    static int carNumber;
    
    public static int getVehileNumber() {
        return carNumber;
    }}
    

    This is because, here we are not overriding a method but we are just re-declaring it. Java allows re-declaration of a method (static/non-static).

    Removing the static keyword from getVehileNumber() method of Car class will result into compilation error, Since, we are trying to change the functionality of static method which belongs to Vehicle class only.

    Also, If the getVehileNumber() is declared as final then the code will not compile, Since the final keyword restricts the programmer from re-declaring the method.

    public static final int getVehileNumber() {
    return VIN;     }
    

    Overall, this is upto software designers for where to use the static methods. I personally prefer to use static methods to perform some actions without creating any instance of a class. Secondly, to hide the behaviour of a class from outside world.

提交回复
热议问题