Generation

code to explanationMon, 20 Mar 2023

class Animals { public void animalsSound() { System.out.println("The animals makes a sound"); } } class cat extends Animals { public void animalsSound() { System.out.println("The cat says: meow meow"); } } class frog extends Animals { public void animalsSound() { System.out.println("The frog says: croak croak "); } } class chicken extends Animals { public void animalsSound () { System.out.println("the chicken say: kokoroko"); } } class Main { public static void main(String[] args) { Animals myAnimals = new Animals(); Animals mycat = new cat(); Animals myfrog = new frog(); Animals mychicken = new chicken (); myAnimals.animalsSound(); mycat.animalsSound(); myfrog.animalsSound(); mychicken.animalsSound();

In the above program, there is a base class Animal which is inherited by different classes like Cat, Frog and Chicken. The method animalSound() is overridden in all the three classes. This is called method overriding. Method overriding is a very important feature of OOP. For example, if we have a parent class Shape with a method draw(), we could have child classes like Circle, Square and Triangle, each implementing a different version of the draw() method.

Questions about programming?Chat with your personal AI assistant