2013-07-22 1 views
6

슈퍼 클래스 목록에서 서브 클래스를 얻기 :자바 : 나는 자바에 새로 온 사람과 2 개 다음 코드에 대한 질문이

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*/); 
    } 
} 

한 것은)로부터 어느 개 또는 고양이 인스턴스를 얻을 방법이 있나요 아미 너리스트? 2) 그렇다면 어떻게 getCertainAnimals 메소드를 올바르게 빌드해야합니까?

+1

instanceof 연산자를 사용하십시오. http://www.javapractices.com/topic/TopicAction.do?Id=31. – kosa

+1

클래스의 유형을 얻으려면 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를 사용하지 않는 경우 컴파일하지만, 그것은 또한 당신이 aRat 경우에도, Cat 또는 Doga 캐스팅 할 수 있습니다. 컴파일 중에도 런타임에 ClassCastException이 표시됩니다. 따라서 instanceof을 사용해야합니다.

+1

감사합니다. – user2605421

+1

문제 없습니다. 에 오신 것을 환영합니다. [tour] (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"); 
     } 
    } 

또한 동물의 종류를 확인하고 동물 하위 클래스와 비교할 수 뭔가를 할 수 있습니다. 당신은 기본적으로

Animal is a Dog 
Animal is a Cat 

으로 출력을 얻을 것이다 두 경우 모두

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

에서와 같이 모두 같은 일을한다. 당신에게 더 나은 이해를주기 위해서.

관련 문제