嗨,我想知道我的问题是否有一个简单的解决方案,
我有一个ArrayList:
ArrayList <Animal> animalList = new ArrayList<Animal>();
/* I add some objects from subclasses of Animal */
animalList.add(new Reptile());
animalList.add(new Bird());
animalList.add(new Amphibian());
Run Code Online (Sandbox Code Playgroud)
它们都实现了一种方法move()- 被叫Bird时的苍蝇move().我知道我可以通过使用它来访问超类的常用方法和属性
public void feed(Integer animalIndex) {
Animal aAnimal = (Animal) this.animalList.get(animalIndex);
aAnimal.eat();
}
Run Code Online (Sandbox Code Playgroud)
这很好 - 但现在我想访问move()子类Bird具有的方法.我可以通过将以下内容转换Animal为Bird:
Bird aBird = (Bird) this.animalList.get(animalIndex);
aBird.move();
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我不想这样做,因为这意味着我有3个不同的上述代码集,每个子类型一个Animal.
这似乎有点多余,有更好的方法吗?
我正在向面板动态添加对象,然后添加到我的边框布局.我需要西部,中部和东部的大小相同.这是我到目前为止:
static int width = 300;//Screen width
static int height = width / 16 * 9;//Screen height
static int scale = 3;
private JFrame frame;
//player is an object from a Player Class will an arrayList of Items..
public void LoadPlayer(Player player){
int count = 1;
for (Items i : player.getAllItems()){
JPanel jp= new JPanel();
JLabel jlItem= new JLabel(i.getName());
BorderLayout bl = (BorderLayout) (mainPanel.getLayout()) ;
jp.add(jlItem);
jp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
if (bl.getLayoutComponent(BorderLayout.WEST) == null){
mainPanel.add(jp,BorderLayout.WEST);
jp.setSize(frame.getWidth()/3, height);
System.out.println("adding item " + count+" to …Run Code Online (Sandbox Code Playgroud)