Polymorphism means "one type, many forms". A parent reference can hold a child object, and the correct method runs based on the actual object type at runtime. In automation, WebDriver driver = new ChromeDriver() — driver is declared as WebDriver but behaves as ChromeDriver.
public class Shape {
String name;
Shape(String name) {
this.name = name;
}
double area() {
return 0;
}
}
public class Rectangle extends Shape {
double width, height;
Rectangle(double width, double height) {
super("Rectangle");
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
public class Circle extends Shape {
double radius;
Circle(double radius) {
super("Circle");
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}public class PolymorphismDemo {
public static void main(String[] args) {
// Parent reference, child object
Shape s1 = new Rectangle(5, 3);
Shape s2 = new Circle(4);
// Correct overridden method runs at runtime
System.out.println(s1.name + " area: " + s1.area()); // 15.0
System.out.printf("%s area: %.2f%n", s2.name, s2.area()); // 50.27
// Array of parent type holding different children
Shape[] shapes = { new Rectangle(10, 5), new Circle(7), new Rectangle(3, 3) };
for (Shape s : shapes) {
System.out.println(s.name + ": " + s.area());
}
}
}// This is the pattern you will see in every Selenium project:
// WebDriver is the parent type (interface)
// ChromeDriver, FirefoxDriver are the child types
// WebDriver driver = new ChromeDriver(); // runs Chrome
// WebDriver driver = new FirefoxDriver(); // runs Firefox
// Same test code works with both because they all implement WebDriver:
// driver.get(url);
// driver.findElement(By.id("x")).click();
// driver.quit();The test code does not care which browser runs. It only uses the WebDriver interface methods. You switch browsers by changing one line — the new ChromeDriver() or new FirefoxDriver() — and the rest of the code works unchanged. This is the power of polymorphism.
Q: What is polymorphism? Give an example from automation.
A: Polymorphism means a parent-type reference can point to different child-type objects, and the correct method executes at runtime based on the actual object. In Selenium: WebDriver driver = new ChromeDriver() — driver is declared as WebDriver but executes ChromeDriver methods. You can swap to FirefoxDriver without changing any test code. This is runtime polymorphism (method overriding).
Exercise 1: Create a Notification class with a send() method. Create EmailNotification, SMSNotification, and PushNotification subclasses. Write a method that takes a Notification parameter and calls send() — pass different subclass objects.
Exercise 2: Create a WebDriverFactory that takes a browser name string and returns the appropriate driver type. Use if/else or switch internally but return the parent type. (Use print statements to simulate different browsers.)