G
G
grazer2020-11-17 18:39:12
Java
grazer, 2020-11-17 18:39:12

Java: how to properly implement an interface?

Hello.
There is an interface CalculateSum which has a single method recieveSum. Also, there is a parent class Animal from which the classes Fish and Bird are inherited. And accordingly enum FISH(5), BIRD(8).
Each of the inherited classes (Fish, Bird) is implemented from the CalculateSum interface.

class Fish extends Animal implements CalculateSum {}
class Bird extends Animal implements CalculateSum {}
public enum Types {
    BIRD(7), FISH(3);

    int type_of_animal = 0;
    Types(int type) {
        this.type_of_animal = type;
    }

    public int getType_of_animal() {
        return type_of_animal;
    }
}


In addition, there is a separate class with methods addAnimal, getAnimal and has an ArrayList in which animals are written according to user-specified data.
For example: the class Fish, which has Types.FISH set, is added to the ArrayList.
Problem with getAnimal method
for (Animal animal : animals_list) {
      if(*здесь своё условие*) {
                *и здесь необходимо вывести на экран recieveSum из класса Bird, либо Fish в зависимости от типа животного*
      }
}

At the same time, the Animal class should not be implemented from CalculateSum, but only the Bird and Fish classes. How to implement it correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nikolaev, 2020-11-19
@grazer

for (Animal animal : animals_list) {
      switch(animal.type_of_animal){
          case "3":
              FISH.reciveSum();
              continue;
          case "7":
              BIRD.reciveSum();
              continue;
    }
}

Approximately the structure is

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question