Selenium Webdriver Day 4 : Inheritance

Inheritance : This is another major properties of OOPS(Object Oriented Programming). In this one class inherit the property of other class.Basically it means derivation of one class from another class, so that the attributes and methods of one class are part of the definition of another class. In this the first class is referred as base class or parent class. The second class is referred as child class or sub-class.
To inherit a class we need use a keyword "extends" in sub-class.

Why we use inheritance in java :
> For method overriding.
> For using methods and variables of one class to another class.
> For code re-usability

Look at the java code below :
public class Parent {
public void parent_method1() {
System.out.println("This is parent method1 ");
}
public void parent_method2() {
System.out.println("This is parent method2 ");
}
public void parent_method3() {
System.out.println("This is parent method3 ");
}
}
This is parent class as we discussed above and here we defined some methods parent_method1(), parent_method2(), parent_method3(). 

To inherit this class we need child class , so  create new child class similar as given below :

//This class inheriting Parent class
public class Child extends Parent{
public void child_method1() {
System.out.println("This is child method 1");
}
public void child_method2() {
System.out.println("This is child method 2");
}
public static void main(String[] args) {
Child ch=new Child();
//Accessing the methods from parent class
ch.parent_method1();
ch.parent_method2();
ch.parent_method3();
//Accessing method from same class
ch.child_method1();
ch.child_method2();
}
}
This is child class here we used extends keyword to inherit the parent class.Now after using extends keyword all the methods of Parent class will be loaded into Child class. Now we can access all those methods just by creating object of base class.
ch.parent_method1();
Here we are creating the object of "Child" class.
ch.parent_method1();
Here we are accessing the methods of parent class just by using child class reference variable.

Now run the Child  class and the output in console will be :
This is parent method1
This is parent method2
This is parent method3
This is child method 1
This is child method 2



Popular posts from this blog

Selenium Webdriver Day 1 : Class and object

Python Programming - Log file is not capturing the data?