如何获取由抽象类扩展的所有类?

时间:2017-12-07 14:03:30

标签: java

我做了一个抽象课。然后我做了3个扩展这个抽象类的类。现在我想在抽象类中创建一个方法,该方法返回一个包含此类扩展的所有类的数组。

public abstract class Item {

String name;
int atk;
int def;

public String getName() {
    return name;
}
public int getAttackValue() {
    return atk;
}
public int getDefenseValue() {
    return def;
}
public static Item[] getAllItems() {
    //TODO
}

public Item(String name, int atk, int def) {
    this.name = name;
    this.atk = atk;
    this.def = def;
}
}

扩展类的示例

public class Sword extends Item{

    public Sword() {
        super("Sword", 15, 0);
    }
}

1 个答案:

答案 0 :(得分:0)

看看这个例子可能对你有帮助:

import java.util.*;

public class Animal{
 public void eat()
 {
  System.out.println("I eat like a generic Animal.");
 }

 public static void main(String[] args)
 {
  List<Animal> animals = new LinkedList<Animal>();

  animals.add(new Animal());
  animals.add(new Wolf());
  animals.add(new Fish());
  animals.add(new Goldfish());
  animals.add(new OtherAnimal());

  for (Animal currentAnimal : animals)
  {
     currentAnimal.eat();
  }
  }
 }

 public class Wolf extends Animal
 {
@Override
 public void eat()
 {
  System.out.println("I eat like a wolf!");
 }
}

public class Fish extends Animal
{
 @Override
 public void eat()
 {
   System.out.println("I eat like a fish!");
 }
}

 public class Goldfish extends Fish
 {
 @Override
 public void eat()
 {
  System.out.println("I eat like a goldfish!");
 }
}

public class OtherAnimal extends Animal {}