Java – Inheritance

by seetaram on July 1, 2011

Knowledge of inheritance really helps if you are using Java / JUnit / TestNG frameworks for Test Automation.  Inheritance is an Object Oriented Programming concept.

If a class which already created contains some variables and methods, if we want to add some more features to the existing class by adding some more functionalities then we should use Inheritance.

[For more information on classes, objects, and methods please visit – Java Concepts]

Let us have a look at the following code:

package com.selftechy.learnjava;

public class UserActions {
	
	public void click(String objname){
		System.out.println("Clicked on "+objname);
	}

	public void select(String objname, String value){
		System.out.println("Value - "+value+"is selected from dropdown "+objname);
	}
	
}

The above example code contains class – UserActions and methods – click and select.  If we need to add some more methods to this class, then there is no need to go ahead and change the existing code but we can write one more class which inherits the properties of this class and also includes some more features.  Go through the following code that gives you a glimpse of the power of “Inheritance”.

package com.selftechy.learnjava;

public class WebAppActions extends UserActions {

	public void type(String objname, String value){
		System.out.println("Typing the value "+value+" into "+objname);
	}

	public void check(String objname, String checkflag){
		System.out.println("Checking the checkbox "+checkflag);
	}
}

The difference between both the classes is the keyword “extends”.  This specifies Java compiler that the class WebAppActions is inheriting the properties of the class UserActions.

We have added two more methods – type and check without changing the existing code.  We can use this feature of Java in Test Automation with Selenium and that will be very much useful.

Leave a Comment

Previous post:

Next post:

Do you want to get updates on the recent articles written? Please subscribe to RSS feed or Email