Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3275824
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T19:11:16+00:00 2026-05-17T19:11:16+00:00

Animal public abstract class Animal { String name; public Animal(String name) { this.name =

  • 0

Animal

public abstract class Animal {
 String name;

 public Animal(String name) {
  this.name = name;
 }

}

Lion

public class Lion extends Animal {

 public Lion(String name) {
  super(name);
  // TODO Auto-generated constructor stub
 }

 public void roar() {
  System.out.println("Roar");
 }
}

Deer

public class Deer extends Animal {

 public Deer(String name) {
  super(name);
 }

 public void runAway() {
  System.out.println("Running...");
 }

}

TestAnimals

public class TestAnimals {
 public static void main(String[] args) {
  Animal lion = new Lion("Geo");
  Animal deer1 = new Deer("D1");
  Animal deer2 = new Deer("D2");

  List<Animal> li = new ArrayList<Animal>();
  li.add(lion);
  li.add(deer1);
  li.add(deer2);
  for (Animal a : li) {
   if (a instanceof Lion) {
    Lion l = (Lion) a;
    l.roar();
   }
   if (a instanceof Deer) {
    Deer l = (Deer) a;
    l.runAway();
   }

  }
 }
}

Is there a better way to iterate through the list without having to cast ?In the above case it seem’s ok but if you have many extensions of the base class then we’ll need that many if block too.Is there a design pattern or principle to address this problem ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T19:11:16+00:00Added an answer on May 17, 2026 at 7:11 pm

    An elegant way of avoiding instanceof without inventing some new artificial method in the base class (with a non-descriptive name such as performAction or doWhatYouAreSupposedToDo) is to use the visitor pattern. Here is an example:

    Animal

    import java.util.*;
    
    abstract class Animal {
        String name;
    
        public Animal(String name) {
            this.name = name;
        }
    
        public abstract void accept(AnimalVisitor av);  // <-- Open up for visitors.
    
    }
    

    Lion and Deer

    class Lion extends Animal {
        public Lion(String name) {
            super(name);
        }
        public void roar() {
            System.out.println("Roar");
        }
    
        public void accept(AnimalVisitor av) {
            av.visit(this);                            // <-- Accept and call visit.
        }
    }
    
    
    class Deer extends Animal {
    
        public Deer(String name) {
            super(name);
        }
    
        public void runAway() {
            System.out.println("Running...");
        }
    
        public void accept(AnimalVisitor av) {
            av.visit(this);                            // <-- Accept and call visit.
        }
    
    }
    

    Visitor

    interface AnimalVisitor {
        void visit(Lion l);
        void visit(Deer d);
    }
    
    class ActionVisitor implements AnimalVisitor {
    
        public void visit(Deer d) {
            d.runAway();
        }
    
        public void visit(Lion l) {
            l.roar();
        }
    }
    

    TestAnimals

    public class TestAnimals {
        public static void main(String[] args) {
            Animal lion = new Lion("Geo");
            Animal deer1 = new Deer("D1");
            Animal deer2 = new Deer("D2");
    
            List<Animal> li = new ArrayList<Animal>();
            li.add(lion);
            li.add(deer1);
            li.add(deer2);
            for (Animal a : li)
                a.accept(new ActionVisitor());         // <-- Accept / visit.
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Lets say I have the following code: abstract class Animal case class Dog(name:String) extends
i have code like this public class People { public string name { get;
I frequently find myself creating classes which use this form (A): abstract class Animal
I have a class Animal and an interface it inherits from IAnimal. @MappedSuperclass public
Consider this example (typical in OOP books): I have an Animal class, where each
Sample 1: class Animal { public static void saySomething() { System.out.print( Gurrr!); } }
(Django 1.x, Python 2.6.x) I have models to the tune of: class Animal(models.Model): pass
I have two parallel inheritance chains: Chain1: Animal <- Lion <- Gazelle Chain2: Food
Possible Duplicate: When to use virtual destructors? let's say i have an abstract class
I have two classes: a base class (Animal) and a class deriving from it

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.