Gg
Tue Jul 09 2024 02:59:38 GMT+0000 (Coordinated Universal Time)
Saved by @chinnu
// Abstract class Animal abstract class Animal { // Properties String name; int age; // Constructor public Animal(String name, int age) { this.name = name; this.age = age; } // Abstract method public abstract void sound(); // Method public void sleep() { System.out.println(name + " is sleeping."); } // Method to display details of the animal public void displayDetails() { System.out.println("Name: " + name + ", Age: " + age); } } // Child class Dog inheriting from Animal class Dog extends Animal { // Additional property String breed; // Constructor public Dog(String name, int age, String breed) { // Call to parent class constructor super(name, age); this.breed = breed; } // Method overriding @Override public void sleep() { System.out.println(name + " the dog is sleeping."); } @Override public void sound() { System.out.println(name + " says Woof!"); } // Additional method specific to Dog public void bark() { System.out.println(name + " is barking."); } @Override public void displayDetails() { super.displayDetails(); System.out.println("Breed: " + breed); } } // Child class Cat inheriting from Animal class Cat extends Animal { // Additional property String color; // Constructor public Cat(String name, int age, String color) { super(name, age); this.color = color; } // Method overriding @Override public void sleep() { System.out.println(name + " the cat is sleeping."); } @Override public void sound() { System.out.println(name + " says Meow!"); } // Additional method specific to Cat public void meow() { System.out.println(name + " is meowing."); } @Override public void displayDetails() { super.displayDetails(); System.out.println("Color: " + color); } } // Main class public class Main { public static void main(String[] args) { // Create instances of Animal Animal[] animals = new Animal[3]; animals[0] = new Dog("Buddy", 3, "Labrador"); animals[1] = new Cat("Whiskers", 2, "White"); animals[2] = new Dog("Rex", 4, "German Shepherd"); // Display details and demonstrate polymorphism for (Animal animal : animals) { animal.displayDetails(); animal.sleep(); animal.sound(); System.out.println(); } } }
Comments