WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Software Engineering · Intermediate · question 25 of 100

Explain the concept of polymorphism in object-oriented programming and provide an example.?

📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

Polymorphism is a fundamental concept in Object-Oriented Programming. It refers to the ability of objects to take on different forms or behaviors depending on the context in which they are used. In other words, polymorphism allows different objects to be treated as if they were the same type of object.

There are two types of polymorphism:

1. Compile-time polymorphism (or method overloading): It allows multiple methods with the same name but different parameters to exist within the same class. The correct method is determined at compile-time based on the method signature.

2. Runtime polymorphism (or method overriding): It allows different implementations of a method to be called based on the type of object that is calling the method. The correct method is determined at runtime based on the object’s actual type.

Here is an example of runtime polymorphism in Java:

class Animal{
   public void makeSound(){
      System.out.println("Animal sound");
   }
}

class Dog extends Animal{
   public void makeSound(){
      System.out.println("Bark");
   }
}

class Cat extends Animal{
   public void makeSound(){
      System.out.println("Meow");
   }
}

public class Main{
   public static void main(String args[]){
      Animal myAnimal = new Animal();
      Animal myDog = new Dog();
      Animal myCat = new Cat();

      myAnimal.makeSound(); //output: Animal sound
      myDog.makeSound(); //output: Bark
      myCat.makeSound(); //output: Meow
   }
}

In this example, we have an Animal class and two subclasses: Dog and Cat. Each subclass overrides the makeSound() method of the Animal class with its own implementation. In the Main class, we create objects of the Animal, Dog and Cat classes and call the makeSound() method on each object. The output shows that each object’s makeSound() method behaves differently based on the object’s actual type. This is an example of runtime polymorphism.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Software Engineering interview — then scores it.
📞 Practice Software Engineering — free 15 min
📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

All 100 Software Engineering questions · All topics