Fun with Polymorphism in Java!
Meet my Zoo in Java ๐: Output attached ๐
๐ 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();
}}