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
Or am I completely off here and is there a completely different way how I should approach this problem?
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