2013-07-22 6 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*/); 
    } 
} 

1) वहाँ किसी भी तरह से या तो कुत्ता या बिल्ली उदाहरणों प्राप्त करने के लिए है अमीनल सूची? 2) यदि हां, तो मुझे सही ढंग से getCertainAnimals विधि कैसे बनाना चाहिए?

+1

ऑपरेटर का उदाहरण http://www.javapractices.com/topic/TopicAction.do?Id=31 का उपयोग करें। – kosa

+1

कक्षा का प्रकार प्राप्त करने के लिए exampleOf() का उपयोग करें :) – Satya

उत्तर

4
Animal a = animals.get(i); 

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

एनबी: यदि आप instanceof का उपयोग नहीं करते यह संकलन होगा, लेकिन यह भी आप Cat या Dog को a कास्ट करने के लिए, भले ही a एक Rat है की अनुमति देगा। संकलन के बावजूद, आपको रनटाइम पर ClassCastException मिलेगा। तो, सुनिश्चित करें कि आप instanceof का उपयोग करें।

+1

धन्यवाद, इससे मुझे बहुत मदद मिली! – user2605421

+1

कोई समस्या नहीं है। एसओ में आपका स्वागत है आपको [टूर] लेना चाहिए (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 

मूल रूप से आउटपुट मिल जाएगा दोनों एक ही काम करते हैं। बस आपको बेहतर समझ देने के लिए।

संबंधित मुद्दे