Search code examples
javaandroidbigdecimal

Java add method to class


Good morning, I have a custom class cBigDecimal that extends the class BigDecimal. My goal is to use both the methods from the BigDecimal and cBigDecimal class (for example "add" or "multiply", as well as the custom function "percentage"). The problem is that "add" & co. return BigDecimal, and obviously I can't cast it to cBigDecimal... Any ideas? Thanks in advance, Lorenzo


Solution

  • What exactly does your cBigDecimal class do that a BigDecimal doesn't?

    It is a design oversight that BigDecimal can be extended at all. Josh Bloch says in Effective Java 3rd Ed Item 17: "Minimize mutability":

    It was not widely understood that immutable classes had to be effectively final when BigInteger and BigDecimal were written, so all of their methods may be overridden. Unfortunately, this cannot be corrected after the fact while preserving backwards compatibility.

    If all you want to do is to "add a method" to BigDecimal, you can simply create a helper method:

    static BigDecimal percent(BigDecimal b) {
      return b.divide(100);  // Or whatever it does.
    }
    

    Then, you can just deal with plain old BigDecimals everywhere.