2.Write a Java program to create a class called "Dog" with a name and breed attribute. Create two instances of the "Dog" class, set their attributes using the constructor and modify the attributes using the setter methods and print the updated values.
💡Code:
class Dog { private String name; private String breed; // Constructor public Dog(String name, String breed) { this.name = name; this.breed = breed; } // Getter methods public String getName() { return name; } public String getBreed() { return breed; } // Setter methods public void setName(String name) { this.name = name; } public void setBreed(String breed) { this.breed = breed; } } class pro2 { public static void main(String[] args) { // Creating two instances of the Dog class Dog dog1 = new Dog("Buddy", "Labrador"); Dog dog2 = new Dog("Max", "German Shepherd"); // Printing initial values System.out.println("Initial Values:"); System.out.println("Dog 1 - Name: " + dog1.getName() + ", Breed: " + dog1.getBreed()); System.out.println("Dog 2 - Name: " + dog2.getName() + ", Breed: " + dog2.getBreed()); // Modifying attributes using setter methods dog1.setName("Charlie"); dog2.setBreed("Golden Retriever"); // Printing updated values System.out.println("\nUpdated Values:"); System.out.println("Dog 1 - Name: " + dog1.getName() + ", Breed: " + dog1.getBreed()); System.out.println("Dog 2 - Name: " + dog2.getName() + ", Breed: " + dog2.getBreed()); } }
📸Output :
