2013-07-22 13 views
6

Jestem nowy Java i mieć 2 pytania o następującym kodzie:Java: Uzyskiwanie podklasę z nadklasy listy

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) Czy istnieje jakiś sposób, aby uzyskać albo pies lub kot instancji od Lista Aminal? 2) Jeśli tak, w jaki sposób należy poprawnie zbudować metodę getCertainAnimals?

+1

Użyj operatora instanceof http://www.javapractices.com/topic/TopicAction.do?Id=31. – kosa

+1

użyj instanceOf(), aby uzyskać typ klasy :) – Satya

Odpowiedz

4
Animal a = animals.get(i); 

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

NB: To skompilować jeśli nie używać instanceof, ale pozwoli również na odlew a do Cat lub Dog, nawet jeśli a jest Rat. Pomimo kompilacji, dostaniesz ClassCastException w czasie wykonywania. Dlatego upewnij się, że używasz instanceof.

+1

Dzięki, bardzo mi pomogło! – user2605421

+1

Bez problemu. Witamy w SO. Powinieneś wziąć [wycieczkę] (http://stackoverflow.com/about). –

2

Można zrobić coś jak następuje

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"); 
     } 
    } 

Można również sprawdzić dla klasy zwierzęcia i porównać ją z klas sub Zwierząt. Jak w

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"); 
    } 
} 

W obu przypadkach otrzymasz wyjść jako

Animal is a Dog 
Animal is a Cat 

Zasadniczo oba robią to samo. Tylko po to, abyś mógł lepiej zrozumieć.

Powiązane problemy