I am trying to add some convenience methods to Java's BigDecimal and create a CustomBigDecimal class. Say I want to add a method reciprocal(). I have tried doing this with inheritence as follows:
public class CustomBigDecimal extends BigDecimal
{
.....
.....
public CustomBigDecimal reciprocal()
{
.....
}
}
CustomBigDecimal foo1 = new CustomBigDecimal(1);
CustomBigDecimal foo2 = new CustomBigDecimal(2);
CustomBigDecimal foo2 = foo1.add(foo2); //cannot cast superclass to subclass
The problem with this approach is that I cannot cast a superclass to subclass (for reasons I am well aware of). And all the methods of the superclass return a BigDecimal. I have thought of a solution to solve this using composition as follows:
public class CustomBigDecimal
{
private BigDecimal val;
CustomBigDecimal(BigDecimal val)
{
this.val = val;
}
......
......
public CustomBigDecimal add(CustomBigDecimal augend)
{
return new CustomBigDecimal(val.add(augend.getBigDecimal()));
}
.....
.....
public CustomBigDecimal reciprocal()
{
....
}
}
But if I go with the second approach, I have to write every method of BigDecimal.
Is there a better approach to solve this problem?