Inheritance in Java
The main goal of inheritance is reusability. Inheritance allows one class (subclass/child) to acquire methods and variables of another class (superclass/parent).
Example with Selenium
|
1 2 3 4 5 6 |
public class FirefoxDriver extends RemoteWebDriver { // FirefoxDriver automatically inherits methods from RemoteWebDriver } FirefoxDriver driver = new FirefoxDriver(); driver.get("https://www.google.com"); // get() is inherited from RemoteWebDriver |
Syntax
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Vehicle { void run() { System.out.println("Vehicle is running"); } } class Car extends Vehicle { void drive() { System.out.println("Car is driving"); } } public class Test { public static void main(String[] args) { Car obj = new Car(); obj.run(); // inherited from Vehicle obj.drive(); // defined in Car } } |
Types of Inheritance in Java
1. Single Inheritance
|
1 2 3 4 5 6 7 |
class Father { void work() { System.out.println("Father works"); } } class Son extends Father { void play() { System.out.println("Son plays"); } } |
2. Multilevel Inheritance
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class GrandFather { void wisdom() { System.out.println("GrandFather’s wisdom"); } } class Father extends GrandFather { void work() { System.out.println("Father works"); } } class Son extends Father { void play() { System.out.println("Son plays"); } } public class FamilyTest { public static void main(String[] args) { Son s = new Son(); s.wisdom(); // from GrandFather s.work(); // from Father s.play(); // from Son } } |
3. Multiple Inheritance (Not Supported in Classes)
Java does not allow a class to extend more than one class. This prevents the diamond problem. Instead, multiple inheritance is achieved using interfaces.
|
1 2 3 4 5 6 7 |
interface A { void show(); } interface B { void display(); } class C implements A, B { public void show() { System.out.println("Show from A"); } public void display() { System.out.println("Display from B"); } } |
Special Note: Object Class
In Java, every class implicitly extends the Object class. That’s why methods like toString(), hashCode(), and equals() are available in all classes.
|
1 2 3 4 5 6 7 8 9 10 11 |
class MyClass { int id; } public class Test { public static void main(String[] args) { MyClass obj = new MyClass(); System.out.println(obj.toString()); // Inherited from Object class System.out.println(obj.hashCode()); // Inherited from Object class } } |
Selenium Example with Inheritance
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class RWD { public void get(String url) { System.out.println("Opening: " + url); } } public class FirefoxDriver extends RWD { // inherits get() method } public class IndeedTests { public static void main(String[] args) { FirefoxDriver driver = new FirefoxDriver(); driver.get("https://www.indeed.com"); // Inherited method } } |