How to avoid large if-statements and instanceof

前端 未结 9 2374
盖世英雄少女心
盖世英雄少女心 2020-11-29 05:11

Animal

public abstract class Animal {
 String name;

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

}

Lion<

9条回答
  •  借酒劲吻你
    2020-11-29 05:50

    Here you have a List of animals. Usually when you have a list of Objects, all these objects must be able to do the same thing without being casted.

    So the best two solutions are :

    • Having a common method for the two concrete classes (so defined as abstract in Animal)
    • Separate Lion from Deer from the start, and have two different lists.

提交回复
热议问题