java force an extending class

前端 未结 6 1324
梦毁少年i
梦毁少年i 2020-12-31 00:17

In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

public          


        
相关标签:
6条回答
  • 2020-12-31 00:31

    Probably there it's not possible at compile time, but you can use reflection to check at run time if the desired constructor was declared:

    public abstract class Points {
    
        protected Points() {
            try {
    
                Constructor<? extends Points> constructor = 
                    getClass().getDeclaredConstructor(Object.class);
                if (!Modifier.isPublic(constructor.getModifiers()))
                    throw new NoSuchMethodError("constructor not public");
    
            } catch (SecurityException ex) {
                throw new RuntimeException(ex);
            } catch (NoSuchMethodException ex) {
                throw (NoSuchMethodError) new NoSuchMethodError().initCause(ex);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-31 00:40

    No Constructors aren't inherited, so each Class needs to provide its own, unless you don't specify a constructor and get the default no args constructor.

    0 讨论(0)
  • 2020-12-31 00:45

    You can use a constructor with a parameter in your abstract class (make it protected if you want to dis-allow anonymous subclasses).

    public abstract class Points{
        protected Points(Something parameter){
            // do something with parameter
        }
    }
    

    Doing that, you force the implementing class to have an explicit constructor, as it must call the super constructor with one parameter.

    However, you cannot force the overriding class to have a constructor with parameters. It can always fake the parameter like this:

    public class ExtendPoints extends Points{
        public ExtendPoints(){
            super(something);
        }
    }
    
    0 讨论(0)
  • 2020-12-31 00:47

    As said by others before, the signatue of Constructors cvannot be enforced, but you could enforce a particular set of arguments by using the AbstractFactory pattern instead. Then you can define the create methods of your factory interface to have a particular signature.

    0 讨论(0)
  • 2020-12-31 00:52

    EDIT

    Well, no, its not possible to force the implementation of a constructor with argument.

    0 讨论(0)
  • 2020-12-31 00:54

    If you add a public Points(Object o) {} constructor to Points, you force any subclass constructors to call that super constructor. However I don't think there's no way of ensuring that subclasses use that exact constructor signature.

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