Why doesn't Java allow overriding of static methods?

后端 未结 22 2695
谎友^
谎友^ 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:19

    Easy solution: Use singleton instance. It will allow overrides and inheritance.

    In my system, I have SingletonsRegistry class, which returns instance for passed Class. If instance is not found, it is created.

    Haxe language class:

    package rflib.common.utils;
    import haxe.ds.ObjectMap;
    
    
    
    class SingletonsRegistry
    {
      public static var instances:Map, Dynamic>;
    
      static function __init__()
      {
        StaticsInitializer.addCallback(SingletonsRegistry, function()
        {
          instances = null;
        });
    
      } 
    
      public static function getInstance(cls:Class, ?args:Array)
      {
        if (instances == null) {
          instances = untyped new ObjectMap();      
        }
    
        if (!instances.exists(cls)) 
        {
          if (args == null) args = [];
          instances.set(cls, Type.createInstance(cls, args));
        }
    
        return instances.get(cls);
      }
    
    
      public static function validate(inst:Dynamic, cls:Class)
      {
        if (instances == null) return;
    
        var inst2 = instances[cls];
        if (inst2 != null && inst != inst2) throw "Can\'t create multiple instances of " + Type.getClassName(cls) + " - it's singleton!";
      }
    
    }
    

提交回复
热议问题