Java forces an expanding class

In Java, can I somehow make a class that extends an abstract class implement its constructor with an object as a parameter?

Something like

public abstract class Points { //add some abstract method to force constructor to have object. } public class ExtendPoints extends Points { /** * I want the abstract class to force this implementation to have * a constructor with an object in it? * @param o */ public ExtendPoints(Object o){ } } 
+18
java constructor abstract-class
May 17 '11 at 9:01
source share
6 answers

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

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

By doing this, you force the implementation class to have an explicit constructor, since it must call a super constructor with one parameter.

However, you cannot force an override class to have a constructor with parameters. It can always fake a parameter as follows:

 public class ExtendPoints extends Points{ public ExtendPoints(){ super(something); } } 
+25
May 17 '11 at 9:03
source share

As others have said, the signature of the constructors cannot be forced, but you can apply a specific set of arguments using the AbstractFactory template instead. You can then define the methods for creating your factory interface to have a specific signature.

+5
May 17 '11 at 9:07
source share

No constructors are inherited, so each class must provide its own, unless you specify a constructor and get the default args constructor.

+2
May 17 '11 at 9:04
source share

This is probably not possible at compile time, but you can use reflection to check at runtime if the desired constructor is 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); } } } 
+1
Mar 02 '17 at 22:53 on
source share

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

0
May 17 '11 at 9:07
source share

EDIT

Well, no, its impossible to enforce a constructor with an argument.

-one
May 17 '11 at 9:10
source share



All Articles