Fun with Polymorphism in Java!

Rishikesh VajreRishikesh Vajre
2 min read

๐Ÿš€ Just coded a funny example of polymorphism in Java! ๐ŸŽ‰ Meet my zoo๐Ÿ˜‚๐Ÿ˜‚:

๐Ÿบ Wolf: "I howl at the moon and scare the villagers!"

๐Ÿฑ Cat: "I meow for attention and secretly judge you."

๐Ÿฎ Cow: "I moo peacefully while chewing cud all day."

๐Ÿฆ† Duck: "I quack loudly just because I can!"

Check out the magic of polymorphism script! ๐Ÿ‘‡

#Java #Coding #Polymorphism #ProgrammingFun

package MondayPractice;

abstract class Janwar {

abstract void sound(); // Abstract method to be implemented by subclasses

}

class Wolf extends Janwar {

void sound() { // Implementing abstract method

System.out.println("Wolf says: ๐Ÿบ 'I howl at the moon and scare the villagers!'");

}}

class Cat extends Janwar {

void sound() { // Implementing abstract method

System.out.println("Cat says: ๐Ÿฑ 'I meow for attention and secretly judge you.'");

}}

class Cow extends Janwar {

void sound() {

System.out.println("Cow says: ๐Ÿฎ 'I moo peacefully while chewing cud all day.'");

}}

class Duck extends Janwar {

void sound() {

System.out.println("Duck says: ๐Ÿฆ† 'I quack loudly just because I can!'");

}}

// Polymorphism allows methods to do different things based on the object it is acting upon.

public class PolymorphismAdvanced {

public static void main(String[] args) {

// Array of Janwar references

Janwar[] zoo = {new Wolf(), new Cat(), new Cow(), new Duck()};

System.out.println("Welcome to the Funny Zoo! ๐ŸŽ‰");

System.out.println("Let's hear some animal sounds...");

// Loop through each animal in the zoo and call their sound method

for (Janwar animal : zoo)

animal.sound();

}}

0
Subscribe to my newsletter

Read articles from Rishikesh Vajre directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rishikesh Vajre
Rishikesh Vajre

Software Development Engineer in Test (SDET) | Automation Expert | Quality Assurance Specialist | Java | Selenium | REST API Testing