LearnFrenzy
Sign in Take a free test

Inheritance · Inheritance Programs · Question 8

Zoo feeding schedule with instanceof checks in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Create Animal, Herbivore and Carnivore classes with Elephant, Deer, Lion and Tiger subclasses; for a mixed list, total the food by type using instanceof pattern matching.

Solution
Main.java
import java.util.List;

class Animal {
    protected final String name;
    protected final double weightKg;
    Animal(String name, double weightKg) { this.name = name; this.weightKg = weightKg; }
}

class Herbivore extends Animal {
    Herbivore(String n, double w) { super(n, w); }
    double plantsKg() { return weightKg * 0.04; }
}

class Carnivore extends Animal {
    Carnivore(String n, double w) { super(n, w); }
    double meatKg() { return weightKg * 0.03; }
}

class Elephant extends Herbivore { Elephant(String n, double w) { super(n, w); } }
class Deer extends Herbivore { Deer(String n, double w) { super(n, w); } }
class Lion extends Carnivore { Lion(String n, double w) { super(n, w); } }
class Tiger extends Carnivore { Tiger(String n, double w) { super(n, w); } }

public class Main {
    public static void main(String[] args) {
        List<Animal> zoo = List.of(new Elephant("Gaja", 4000), new Lion("Sher", 190), new Deer("Chital", 60), new Tiger("Bagh", 220));
        double plants = 0, meat = 0;
        for (Animal a : zoo) {
            if (a instanceof Herbivore h) plants += h.plantsKg();
            else if (a instanceof Carnivore c) meat += c.meatKg();
        }
        System.out.printf("plants %.1f kg, meat %.1f kg%n", plants, meat);
        System.out.println(zoo.stream().filter(a -> a instanceof Carnivore).map(a -> a.name).toList());
    }
}

Output Verified by compiling and running

plants 162.4 kg, meat 12.3 kg
[Sher, Bagh]

instanceof Herbivore matches both Elephant and Deer, because they inherit from it. (Polymorphism – a single food() method – is often cleaner; see the next topic.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links