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
- How should I store the 'val' parameter, as Object just doesn't seem like the best way to do this?
- 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?
maybe
Cellis too generic in your case. For example, you might consider having different classes forNumericCellandStringCell:you can keep
Cellas an abstract class or interface and put there the common methods you want all the cells to perform, for examplenow StringCell can implement this and simply return val, while
NumericCellknows it operates on a BigDecimal so it can perform some formatting, for example only display 2 decimals and rounding the number: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