samedi 17 juin 2017

New type of constructor for child class

I'm making API.

Assume that the unique constructor of class A has the parameter int num.

If we define class B extends A, any constructor of class B should call super(int).

My question is, if class B receives another types through its constructor, for instance, public B(String[] names, double coef), how can I pre-generate int num from String[] names, double coef before call super(int)?

In one line, How can I design a constructor of child class of different form from parent class?

I tried

public class B extends A {

    private String[] names;
    private double coef;        

    public B(String[] names, double coef) {
        super(convertToNum(names, coef));
        this.names = names;
        this.coef = coef;
    }

    public static int convertToNum(String[] names, double coef) {
        // Logic for converting params to integer
        return num;
    }
}

but I think this is not a right design of OOP.

Is there any useful design pattern for this case?

Aucun commentaire:

Enregistrer un commentaire