Java abstract static Workaround

前端 未结 15 2014
猫巷女王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 {
        Set widgets = new HashSet();
    
        Set getAll() {
            return widgets;
        }
    
        abstract class Widget {
    
           Widget() {
               widgets.add(this);
           }
    
           abstract String getName();
        }
    
        public static void main(String[] args) {
             WidgetCollection aWidgets = new WidgetCollection();
             a.new AWidget();
    
             Set widgets = aWidgets.getAll();
        }
    }
    
    class AWidget extends Widget {
        String getName() {
            return "AWidget";
        }
    }
    

提交回复
热议问题