Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java force an extending class

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 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){

    }
}
like image 648
Marthin Avatar asked May 17 '11 09:05

Marthin


4 Answers

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);
    }
}
like image 135
Sean Patrick Floyd Avatar answered Nov 18 '22 02:11

Sean Patrick Floyd


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.

like image 36
BertNase Avatar answered Nov 18 '22 04:11

BertNase


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.

like image 2
planetjones Avatar answered Nov 18 '22 03:11

planetjones


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);
        }
    }
}
like image 2
user85421 Avatar answered Nov 18 '22 04:11

user85421