Java – Calling a constructor from a parent class in a derived class

constructorsinheritancejava

I'm trying to create a parent class with a constructor that takes a single int as a parameter. I also need to derive a child class that creates two instances of the parent class using a constructor that takes two ints. I know I use the "super" keyword to use the constructor from the parent class, but how can I use the second int in the child constructor to call the same parent constructor? I can't use "super" twice, so is there any other way to use the second parameter? I know that I could just call the child constructor twice from the main method, but I specifically need a child constructor that takes two parameters and creates two objects of the parent class. Thanks.

public class Int 
{   
    public int numberOne;

    public Int(int numberHere)
    {
        numberOne = numberHere;
    }

    //methods...
}   



public class Rational extends Int
{
    Int numerNum;
    Int denomNum;

    public Rational(int oneHere, int twoHere)
    {
        super(oneHere);
    }

    //methods...
}

Best Answer

You're trying to use inheritance when you need to be using composition.

Use this as a starting point instead:

public class Rational {

    private Int numerator;
    private Int denominator;

    public Rational(int num, int den) {
        numerator = new Int(num);
        denominator = new Int(den);
    }
}

As a general rule of thumb, inheritance is best used for "Is-a" relationships. Ask yourself, "Is a rational number an integer?" The answer is clearly no.

Related Topic