Chapter 3 |
An array of objects
In the previous sections, we have declared and created single instances (e.g. Dog liza and Dog marfa). However, we can also create an array of these instances since they are of the same data type.
Examine the following application:
File name: Dog.java
// Object class declaration public class Dog { // Instance fields private String name; private String breed; private int age; private String size; private String color; private String accent = "bow-wow"; // Constructor public Dog(String name, String breed, int age, String size, String color) { this.name = name; this.breed = breed; this.age = age; this.size = size; this.color = color; } // Default constructor public Dog() { this("No name","Unknown",0,"Unknown","Unknown"); } // Add getters (accessor methods) public String getName() { return name; } public String getBreed() { return breed; } public String getSize() { return size; } public int getAge() { return age; } public String getColor() { return color; } public String getAccent() { return accent; } // Add setters (mutator methods) public void setName(String name) { this.name = name; } public void setBreed(String breed) { this.breed = breed; } public void setSize(String size) { this.size = size; } public void setAge(int age) { this.age = age; } public void setColor(String color) { this.color = color; } public void setAccent(String accent) { this.accent = accent; } // Object behavior (methods) public String woofing() { return ("The dog "+name+" makes sound like "+accent); } public String toString() { return "Name: "+name+" Breed: "+breed+" Size: "+size+" Age: "+age+" Color: "+color +" Accent: "+accent; } }
File name: Execution.java
public class Execute { // main method public static void main(String[] args) { // Create an instance of the object class for labrador Liza Dog liza = new Dog("Liza","labrador",3,"small","brown"); System.out.println(liza.woofing()); Dog marfa = new Dog("Marfa", "beagle", 5, "small", "yellow-white-black"); System.out.println(marfa.getBreed()); // An array of objects Dog[] pet_shop = {liza, marfa}; // Print the info about each dog in the pet shop for (Dog d: pet_shop) { System.out.println(d); } } }
Chapter 3 |