2013-07-22 3 views
6

Я новый с Явы и есть 2 вопроса о следующем коде:Java: Получение подкласса от суперкласса списка

class Animal { } 
class Dog extends Animal { } 
class Cat extends Animal { } 
class Rat extends Animal { } 

class Main { 
    List<Animal> animals = new ArrayList<Animal>(); 

    public void main(String[] args) { 
    animals.add(new Dog()); 
    animals.add(new Rat()); 
    animals.add(new Dog()); 
    animals.add(new Cat()); 
    animals.add(new Rat()); 
    animals.add(new Cat()); 

    List<Animal> cats = getCertainAnimals(/*some parameter specifying that i want only the cat instances*/); 
    } 
} 

1) Есть ли способ, чтобы получить либо собака или кошка экземпляры из Аминальный список? 2) Если да, то как я должен правильно построить метод getCertainAnimals?

+1

Использование экземпляра оператора http://www.javapractices.com/topic/TopicAction.do?Id=31. – kosa

+1

use instanceOf(), чтобы получить тип класса :) – Satya

ответ

4
Animal a = animals.get(i); 

if (a instanceof Cat) 
{ 
    Cat c = (Cat) a; 
} 
else if (a instanceof Dog) 
{ 
    Dog d = (Dog) a; 
} 

NB: Это будет собирать, если вы не используете instanceof, но это также позволит вам бросить a к Cat или Dog, даже если a является Rat. Несмотря на компиляцию, вы получите ClassCastException во время выполнения. Поэтому убедитесь, что вы используете instanceof.

+1

Спасибо, мне это очень помогло! – user2605421

+1

Нет проблем. Добро пожаловать в SO. Вы должны взять [тур] (http://stackoverflow.com/about). –

2

Вы можете сделать что-то вроде следующего

List<Animal> animalList = new ArrayList<Animal>(); 
    animalList.add(new Dog()); 
    animalList.add(new Cat()); 
    for(Animal animal : animalList) { 
     if(animal instanceof Dog) { 
      System.out.println("Animal is a Dog"); 
     } 
     else if(animal instanceof Cat) {; 
      System.out.println("Animal is a Cat"); 
     } 
     else { 
      System.out.println("Not a known animal." + animal.getClass() + " must extend class Animal"); 
     } 
    } 

Вы также можете проверить для класса животных и сравнить его с животными подразделов классов. Как и в

for(Animal animal : animalList) { 
    if(animal.getClass().equals(Dog.class)) { 
     System.out.println("Animal is a Dog"); 
    } 
    else if(animal.getClass().equals(Cat.class)) {; 
     System.out.println("Animal is a Cat"); 
    } 
    else { 
     System.out.println("Not a known animal." + animal.getClass() + " must extend class Animal"); 
    } 
} 

В обоих случаях вы получите выходы, как

Animal is a Dog 
Animal is a Cat 

В принципе оба делают то же самое. Просто чтобы лучше понять.

Смежные вопросы