Enhanced For Loop - Array of Objects

前端 未结 3 1869
南方客
南方客 2021-02-06 05:42

Ok so I have a class called Dog() which takes two parameters, a string and an integer.
This class has a method called bark(), which prints a string depending on the intege

相关标签:
3条回答
  • 2021-02-06 06:06

    Just use it in the for each

    for(Dog d : kennel) {
        d.bark();
    }
    
    0 讨论(0)
  • 2021-02-06 06:12

    About your second question:"Why do I have to start with Dog[] ... new Dog[5]?"

    Its because of same logic you have to put Dog dog=new Dog(); ----(1) That's why Dog[] dogArray=new Dog[5]; ---(2)

    If you don't have problem with the first one then why crib about the second one.

    0 讨论(0)
  • 2021-02-06 06:14

    Here's how you do it using enhanced for loop.

    for(Dog dog : kennel) {
        dog.bark();
    }
    

    For your other question, if you're going to be using arrays, you'll have to declare the size before you start adding elements to it. One exception, however is if you are doing both initialization and declaration in the same line. For example:

    Dog[] dogs = {new Dog("Harold", 1), new Dog("Arnold", 2)};
    
    0 讨论(0)
提交回复
热议问题