Java abstract static Workaround

前端 未结 15 1926
猫巷女王i
猫巷女王i 2020-12-29 04:43

I understand that neither a abstract class nor an interface can contain a method that is both abstract and static because of ambiguity problems, but is there a workaround?

相关标签:
15条回答
  • 2020-12-29 05:21

    I'd make a WidgetCollection class with an abstract Widget inner class.

    You can extend the WidgetCollection.Widget class for each of your types of Widget.

    No static methods necessary.

    Example (not compiled or tested):

    class WidgetCollection<W extends Widget> {
        Set<W> widgets = new HashSet<W>();
    
        Set<W> getAll() {
            return widgets;
        }
    
        abstract class Widget {
    
           Widget() {
               widgets.add(this);
           }
    
           abstract String getName();
        }
    
        public static void main(String[] args) {
             WidgetCollection<AWidget> aWidgets = new WidgetCollection<AWidget>();
             a.new AWidget();
    
             Set<AWidget> widgets = aWidgets.getAll();
        }
    }
    
    class AWidget extends Widget {
        String getName() {
            return "AWidget";
        }
    }
    
    0 讨论(0)
  • 2020-12-29 05:22

    Is there a way to do this in Java?

    I don't think there is a way to do this in any language. There's no point to it, since static methods belong to a class and can't be called polymorphically. And enabling polymorphic calls is the only reason for interfaces and abstract classes to exist.

    0 讨论(0)
  • 2020-12-29 05:23

    Ok, maybe my question was poorly asked, it seems like most of you didn't get what I was trying to do. Nonetheless, I have a solution that is somewhat satisfactory.

    In the abstract super class, I am going to have a static method getAllWidgets(Class type). In it I'll check the class you passed it and do the correct fetching based on that. Generally I like to avoid passing around classes and using switches on stuff like this, but I'll make an exception here.

    0 讨论(0)
提交回复
热议问题