Java Exercise
In this exercise, you will create a Java program that defines a base class named Animal
with common attributes such as name
and age
, and methods for accessing these attributes. You will then create a derived class named Dog
that inherits from the Animal
class and overrides the makeSound()
method to provide a dog-specific implementation. The goal is to understand how inheritance allows you to reuse code and extend the functionality of classes in Java.
Instructions:
- Create a base class named
Animal
with the attributes name
and age
, and getters
and setters
methods for these attributes.
- Create a derived class named
Dog
that inherits from the Animal
class and overrides the makeSound()
method to make it play a dog-specific sound, such as "Woof!".
- In the main method, create an object of the
Dog
class, set its name and age, and call the makeSound()
method to demonstrate the behavior. Overridden.
This exercise will help you understand how to **inherit** functionality from a base class to a derived class, how to override methods, and how to use inheritance to promote code reuse in Java.
View Example Code
public class Animal {
// Common attributes
private String name;
private int age;
// Constructor
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Method to be overridden
public void makeSound() {
System.out.println("The animal makes a sound.");
}
}
public class Dog extends Animal {
// Constructor that inherits from Animal
public Dog(String name, int age) {
super(name, age);
}
// Override the makeSound method
@Override
public void makeSound() {
System.out.println("Woof!");
}
public static void main(String[] args) {
// Create an object of the Dog class
Dog dog = new Dog("Rex", 5);
// Display the dog's details
System.out.println("Name: " + dog.getName());
System.out.println("Age: " + dog.getAge() + " years");
// Call the overridden method
dog.makeSound();
}
}
Output:
Name: Rex
Age: 5 years old
Wow!
This program shows how to inherit functionality from a base class to a derived class, and how to override methods to customize the behavior of a derived class in Java. This concept of inheritance is key in object-oriented programming for reusing and extending code.