0

如果我有一个描述例如的类。people,命名为 Person,然后它有 6 个子类,例如 Child、Adult Man、Adult Woman 等。他们都有 ID、头发颜色、眼睛颜色等。只是他们的外观不同,所以我所有的子类都包含他们的自己的paint() 方法。每个人都有两个坐标来告诉程序必须在框架上绘制它们的位置,所有子类都得到这些坐标,如下所示:

class AdultMan extends Person
{
    AdultMan(int x, int y) {
        super(x,y); 
            // I haven't yet worked with the hair color, eye color...
            // only the coordinates to test my idea out
    }

    public void paint(Graphics g) {
            int x = getX();
            int y = getY();
            // The drawing of an adult man from basic shapes 
            // based on the given coordinates (and colors later)
    }
}

因此,在我处理给定数据的另一个类中,我将它们全部放在一个地图中Map<Integer,Person> (整数是 ID),然后在一个扩展 Jframe 的类中,我将地图的值放在一个集合中并像这样迭代它们:

for (Person person : persons) 
{
  // (persons is the name of my collection)
  if(person.typeName.equals("adultMan"))
  {
     person = new AdultMan(person.x,person.y);
     person.paint(g);
  }
}

我有 6 种类型的人,所以我想对每种类型都这样做。问题是,如果我的地图中最多有 40 人,则可能有 30 个人左右,这只会在框架上绘制第一个并跳到下一个不同的类型。

4

1 回答 1

1

这不完全是您问题的答案,但您似乎误解了继承在 Java 中的工作方式。

如果您有一个类Person和一个AdultMan继承它的类,这意味着您应该能够在任何可以使用a的地方使用 a的实例。这就是LSP的精髓。因此,如果一个方法具有以下签名:AdultManPerson

public void tickle(Person p)

然后,您可以使用 AdultMan(或任何其他类继承 Person 的对象)调用该方法。同样在 Java 中,如果子类定义了与超类相同的方法签名,则称为覆盖该方法。下面的代码说明了这一点:

class Person {
   public void laugh() {
       System.out.pring("Tihi");
   }
}  

class AdultMan extends Person {
   public void laugh() {
       System.out.pring("Hahaha");
   }
}

class AdultWoman extends Person {
   public void laugh() {
       System.out.pring("Hihihi");
   }
}

class Child extends Person { }

AdultManAdultWoman覆盖该laugh方法,因此每当在这些类的实例laugh上调用该方法时,都会调用该类的方法。持有该对象的变量的类型是否为 a 无关紧要。如果有一个方法覆盖了获得调用的方法的笑声方法。在类的情况下,它没有定义自己的方法,因此只是从 Person 继承了方法。说明这一点的可运行示例是:PersonChildlaugh

public class App {
    public static void main(String[] args) {
        Person person = new Person();
        Person man = new AdultMan();
        Person woman = new AdultWoman();
        Person child = new Child();
        List<Person> persons = new ArrayList();
        persons.add(person);
        persons.add(man);
        persons.add(woman);
        persons.add(child);

        for(Person p : persons) {
            System.out.print("Laugh: ");
            p.laugh();
        }
        // This will print:
        // Laugh: Tihi
        // Laugh: Hahaha
        // Laugh: Hihihi
        // Laugh: Tihi
    }
}
于 2012-12-25T15:45:28.070 回答