Inheritance Reviewer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Main.

java

public class Main {

public static void main(String[] args) {

// Create a Dog object

Dog dog = new Dog("Penpen", 1, "Shitzu");

// Create a Cat object

Cat cat = new Cat("desarapen", 2, "Siamesse");

// Display details of Dog and Cat

System.out.println("Dog Details:");

dog.display();

System.out.println("\nCat Details:");

cat.display();

Animal.java

public class Animal {

// Attributes of an animal

private String name;

private int age;

// Constructor

public Animal(String name, int age) {

this.name = name;

this.age = age;

// Method to display animal details

public void display() {

System.out.println("Animal: " + name);


System.out.println("Age: " + age);

// Getter methods

public String getName() {

return name;

public int getAge() {

return age;

Dog.java

public class Dog extends Animal {

// Additional attribute for Dog

private String breed;

// Constructor

public Dog(String name, int age, String breed) {

// Call the constructor of the superclass (Animal)

super(name, age);

this.breed = breed;

// Method to display dog details

@Override

public void display() {

// Call the display method of the superclass

super.display();

System.out.println("Breed: " + breed);

}
Cat.java

public class Cat extends Animal {

// Additional attribute for Cat

private String color;

// Constructor

public Cat(String name, int age, String color) {

// Call the constructor of the superclass (Animal)

super(name, age);

this.color = color;

// Method to display cat details

@Override

public void display() {

// Call the display method of the superclass

super.display();

System.out.println("Color: " + color);

Output:

You might also like