javaxssf

Java multiple constructors with different data types, oke or not, and how to handle?


I have a class called 'Cell' in which I (think I) need multiple constructors

The goal is to add the cell's later to an excel sheet, when adding to an excel sheet you need to add what type of data to set the excell-cell to and therefor I want to retrieve the data type from the cell class

public Object val;

public Cell (BigDecimal val)
{
    this.val = val;
}

public Cell (String val)
{
    this.val = val;
}

public Cell (int val)
{
    this.val = val;
}

I have 2 questions

  1. How should I store the 'val' parameter, as Object just doesn't seem like the best way to do this?
  2. If I store 'val', how can I later find back what data type 'val' is/was ?

Or am I completely off here and is there a completely different way how I should approach this problem?


Solution

  • maybe Cell is too generic in your case. For example, you might consider having different classes for NumericCell and StringCell:

    class NumericCell implements Cell {
        private BigDecimal val;
    
        public NumericCell (BigDecimal val) {
            this.val = val;
        }
    
        public NumericCell (int val) {
            this(BigDecimal.valueOf(val));
        }
    }
    
    class StringCell implements Cell {
        private String val;
    
        public StringCell (String val) {
            this.val = val;
        }
    }
    

    you can keep Cell as an abstract class or interface and put there the common methods you want all the cells to perform, for example

    interface Cell {
        String content();
    }
    

    now StringCell can implement this and simply return val, while NumericCell knows it operates on a BigDecimal so it can perform some formatting, for example only display 2 decimals and rounding the number:

    @Override
    public String content() {
        return val.setScale(2, RoundingMode.FLOOR).toString();
    }
    

    This is called polymorphism and it is a very powerful tool in OOP. you can read more about it here: https://www.w3schools.com/java/java_polymorphism.asp