Home » Java » java – How do i differentiate different subclasses in a array of the superclass?-Exceptionshub

java – How do i differentiate different subclasses in a array of the superclass?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

My setup is the following.
I have a superclass called “bottles” and 2 different subclasses, “water” and “soda”. There’s an array filled with countless of both of these and my goal is to write a method that returns the total liter values of only one of these subclasses. What would be the best way to accomplish that? As far as i understand ‘instanceof’ has no use here.

To clarify i only want to know what operator/method is used to compare:

if (bottles[0]==soda){
      ...
}
How to&Answers:

IIRC, instanceof still works.

However, how about you put the logic of your counting-liter-criteria in your subclass method? So that, if you want to count the liter of sweet drink in your bottles, your water should return 0 but your soda should return real liter. Since the subclasses know the best of itself, it is better you let them give you the answer directly. Don’t break encapsulation.

Answer:

if(bottles[i] instanceof Soda) {
    return bottles[i].getRealLiter();
    }
 else if(bottles[i] instanceof Water) {
    return 0;
}

Answer:

Generally if you have control over Bottle classes and you still need to use instanceof in your code, you have problems with your design.

interface Bottle{
  void addLiters(LiterCalculator calculator);
}

LiterCalculator will look something like this,

interface LiterCalculator{
   public addWater(int liters);
   public addSoda(int liters);
   //so on
}

And SodaBottle is responsible of adding itself;

class SodaBottle implements Bottle {
private int liters;

public void addLiters(LiterCalculator calculator) { calculator.addSoda(liters); }
}

So your flow is no longer responsible of different calculations of Bottle instances.