OOP: Polymorphism in Java

Car class is parent class of BMW and Audi
Car car = new BMW();// orCar car2 = new Audi();
Car car =
= new BMW(); 
= new Audi();
public class Car {
public String model;
public double sdeed;

public void drive() {
System.out.println("Car is driving");
}
public void stop() {
System.out.println("Car is stopping");
}
}
public class BMW extends Car {
@Override
public void drive() {
System.out.println("BMW is driving");
}
public void driveFast() {
System.out.println("BMW is driving fast");
}
}
public class Main {
public static void main(String[] args) {
Car car = new BMW();
car.drive(); // BMW is driving

car.stop(); // Car is stopping
// car.driveFast(); does not compile
}
}
  • car.drive(); will print BMW is driving because the BMW class overrides the parent method. This is also known as runtime polymorphism because java thinks it will execute the method of the Car class but during the runtime, it will figure out that BMW overrides it and will execute BMW’s method.
  • car.stop(); the output will be Car is stopping the parent class method will get called.
  • car.driveFast(); will not compile because. The reference type decides what methods are available for car the object. And Car does not have driveFast(); method.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store