w3resource

Java: Create and Modify Dog Objects

Java OOP: Exercise-2 with Solution

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.

Sample Solution:

Java Code:

// Dog.java
public class Dog {
  private String name;
  private String breed;

  public Dog(String name, String breed) {
    this.name = name;
    this.breed = breed;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getBreed() {
    return breed;
  }

  public void setBreed(String breed) {
    this.breed = breed;
  }
}

The above class has two private attributes: ‘name’ and ‘breed’, and a constructor that initializes these attributes with the values passed as arguments. It also has getter and setter methods to access and modify these attributes.

// Main.java
public class Main {
  public static void main(String[] args) {
    Dog dog1 = new Dog("Buddy", "Golden Retriever");
    Dog dog2 = new Dog("Charlie", "Bulldog");

    System.out.println(dog1.getName() + " is a " + dog1.getBreed() + ".");
    System.out.println(dog2.getName() + " is a " + dog2.getBreed() + ".");

    System.out.println("\nSet the new Breed of dog1 and new name of dog2:");
    dog1.setBreed("Labrador Retriever");
    dog2.setName("Daisy");

    System.out.println(dog1.getName() + " is now a " + dog1.getBreed() + ".");
    System.out.println(dog2.getName() + " is now a " + dog2.getBreed() + ".");
  }
}

In the above example code, we create two instances of the "Dog" class, set their attributes through the constructor, and print their name and breed using the getter methods. We also modify the attributes using the setter methods and print the updated values.

Sample Output:

Buddy is a Golden Retriever.
Charlie is a Bulldog.

Set the new Breed of dog1 and new name of dog2:
Buddy is now a Labrador Retriever.
Daisy is now a Bulldog.

Flowchart:

Flowchart: Java  OOP Exercises: Create and Modify Dog Objects.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java OOP Previous: Create and print Person objects.
Java OOP Next: Calculate area and perimeter of a rectangle.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.