Answer
Inheritance in Java
Inheritance is an OOP mechanism where a child class (subclass) acquires the properties and behaviors of a parent class (superclass) using the extends keyword.
Purpose: Code reuse, method overriding, hierarchical classification.
Types of Inheritance in Java
1. Single Inheritance
One child extends one parent.
class Animal {
public void breathe() {
System.out.println("Animal breathes");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Dog barks");
}
}
Dog d = new Dog();
d.breathe(); // inherited
d.bark(); // own method
2. Multilevel Inheritance
Chain: Grandparent → Parent → Child.
class Animal {
public void eat() { System.out.println("Eating"); }
}
class Mammal extends Animal {
public void breatheAir() { System.out.println("Breathing air"); }
}
class Dog extends Mammal {
public void bark() { System.out.println("Woof!"); }
}
Dog d = new Dog();
d.eat(); // from Animal
d.breatheAir(); // from Mammal
d.bark(); // own
3. Hierarchical Inheritance
Multiple children extend the same parent.
class Shape {
public void draw() { System.out.println("Drawing shape"); }
}
class Circle extends Shape {
public double area(double r) { return Math.PI * r * r; }
}
class Rectangle extends Shape {
public double area(double l, double w) { return l * w; }
}
4. Multiple Inheritance — NOT supported via classes
Java does NOT allow a class to extend multiple classes (to avoid the "Diamond Problem").
// ❌ NOT allowed
class C extends A, B { } // compile error
Solution: Use Interfaces (a class can implement multiple interfaces).
interface Flyable { void fly(); }
interface Swimmable { void swim(); }
class Duck implements Flyable, Swimmable {
public void fly() { System.out.println("Duck flies"); }
public void swim() { System.out.println("Duck swims"); }
}
super Keyword
Used to call parent class constructor or methods.
class BasePage {
WebDriver driver;
BasePage(WebDriver driver) {
this.driver = driver;
}
public void waitForElement(By locator) {
new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
}
class LoginPage extends BasePage {
LoginPage(WebDriver driver) {
super(driver); // calls parent constructor
}
public void login(String user, String pass) {
super.waitForElement(By.id("username")); // calls parent method
driver.findElement(By.id("username")).sendKeys(user);
}
}
Inheritance in Automation Frameworks
// Page Object Model uses inheritance
BasePage
├── LoginPage
├── HomePage
├── ProductPage
└── CheckoutPage
// All inherit WebDriver, wait, and common utility methods from BasePage
