I have a class LargeCell
which is an extension of the Cell
class. I want to use same name for fixed array in both classes with a different array size. In cell class I want the size to be 1 and in LargeCell class I want size to be 2. When I try to add prisoner to LargeCell instead of prisoner being added to LargeCell, he is added to array in Cell class. I can override addPrisonerToCell()
method but it does not seem like the best solution to me since it is copy paste from other class.
Is there any way, to make methods work on the right class without overriding them?
public class Cell {
private int cellNumber;
private Prisoner[] prisoners;
public Cell(int cellNumber){
this.cellNumber=cellNumber;
this.prisoners=new Prisoner[1];
}
public boolean addPrisonerToCell(Prisoner prisoner) {
for(int i=0; i<this.prisoners.length;i++){
if(this.prisoners[i]==null){
this.prisoners[i]=prisoner;
return true;
}
}
return false;
}}
public class LargeCell extends Cell {
private Prisoner[] prisoners;
public LargeCell(int cellNumber) {
super(cellNumber);
this.prisoners = new Prisoner[2];
}
@Override
public boolean addPrisonerToCell(Prisoner prisoner) {
for(int i=0; i<this.prisoners.length;i++){
if(this.prisoners[i]==null){
this.prisoners[i]=prisoner;
return true;
}
}
return false;
}}
By declaring another prisoners
field, you are only shadowing the field from the superclass. You could have the Cell
constructor accept an int specifying the size of the array like so:
public class Cell {
private int cellNumber;
private Prisoner[] prisoners;
public Cell(int cellNumber){
this(cellNumber, 1);
}
protected Cell(int cellNumber, int size){//only accessible by subclasses
this.cellNumber = cellNumber;
this.prisoners = new Prisoner[size];
}
public boolean addPrisonerToCell(Prisoner prisoner) {
for(int i=0; i<this.prisoners.length;i++){
if(this.prisoners[i]==null){
this.prisoners[i]=prisoner;
return true;
}
}
return false;
}
}
public class LargeCell extends Cell {
public LargeCell(int cellNumber) {
super(cellNumber, 2);
}
}