Understanding Access modifiers in java

There are way too many tutorials available out there on Java Access Modifiers, here we will try to relate these access specifiers with selenium webdriver and better understand with examples using Java and selenium webdriver.

We need access modifiers in order to set/control the accessibility of classes, methods and variables. Not all modifiers applicable for all, some are applicable for classes, some are for methods, variables and some for both.

Giving the accessibility for a class specifies the compiler that others classes has the access to use the members of that class. Access Modifiers for a class are public, private, protected and default. And other modifiers which are applicable for class are final, abstract, static and strictfp

"A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package. " Ref-Oracle Docs

Here we will be discussing mainly about public, private and protected, as these modifiers are the most used modifiers when we write our automation scripts. We will discuss other modifiers in later articles.

Public Access Modifier

Public modifier gives the accessibility for a class from other classes within a package or from outside package. public is also declared for methods and variables. when a method or variable is public then the method or variable can be accessed from not only inside the package but also from outside the package.

Example:

package se.java;

public class AddSum {
	public int add(int a, int b){
		int c= a+b;
		return c;	
	}
}
package se.javamodifiers;

import se.java.AddSum;

public class PublicDemo {
	public static void main(String[] args) {
		AddSum as= new AddSum();
		System.out.println("Sum of two numbers is: "+as.add(10, 20));
	}

}

In the above example class PublicDemo is accessing the method add() from the class AddSum. If we have not declared AddSum class as public, we will get compile time error in the class PublicDemo.

Whenever we declare the methods or variables of a class as public, the methods or variables are accessible from outside the package if and only if the class is also declared as public, then only other classes can access the present class members otherwise it will give compile time error. The compiler first checks for the class visibility.

Example:

package se.java;
class PublicDemo1{
	
	public int b=20;
	
	public void demo(){
		System.out.println("Test Method");
	}
}
package se.javamodifiers;

public class PublicDemo {
	public static void main(String[] args) {
		PublicDemo1 pd1= new PublicDemo1();// we get compile time error
		
	}

}

In the above example class PublicDemo is trying to access the class PublicDemo1 which is present in another package. Here we will get compile time error as PublicDemo1 is not declared as public and we are trying to access that class.

In this program even though the methods and variables are declared as public, we cannot access them from other package as there is no class visibility.

Let us look an example for Public access Modifier using Selenium webdriver

First create two classes and name them as ‘Browser.java’ and ‘ChromeTest.java’

In ‘Browser.java’ class we will define a public method ‘getDriver(String browserType)’ which can be accessed by ‘ChromeTest.java’ class to get driver instance based on the browser type that we send.

Class - Browser.java

package com.easy;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class Browser {
	
private String driverPath = "F:/chromedriver/";
public WebDriver driver;
	
	public WebDriver getDriver(String browserType) {
		switch (browserType) {
		case "firefox":
			return	driver = new FirefoxDriver();
		case "chrome":
			System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
			return	driver = new ChromeDriver();
		case "IE":
			System.setProperty("webdriver.ie.driver", driverPath+"IEDriverServer.exe");
			return	driver = new InternetExplorerDriver();
		default:
			System.out.println("browser : " + browserType + " is invalid, Launching Firefox as browser of default choice..");
			return driver = new FirefoxDriver();
		}
	}
}

Class - ChromeExample.java

package com.easy;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.easy.Browser;

public class ChromeExample {

   private WebDriver driver;

  @FindBy(id= "username") private WebElement userName;
  @FindBy(id= "password") private WebElement password;
  @FindBy(id= "login") private WebElement signInBtn;

	@BeforeClass
	public void setUp() {
		System.out.println("launching browser");
		Browser browser = new Browser();
		driver = browser.getDriver("chrome");
		driver.manage().window().maximize();
	}
	
	@Test
	public void testGooglePageTitleInChrome() {
		driver.navigate().to("http://www.google.com");
		String strPageTitle = driver.getTitle();
		Assert.assertTrue(strPageTitle.equalsIgnoreCase("Google"), "Page title doesn't match");
	}

       @Test
	public void testGoogleLogin() {
		driver.navigate().to("http://www.google.com/login");
		userName.sendKeys("test");
                password.sendKeys("xxxxxxxx");
               signInBtn.click();
	}

	@AfterClass
	public void tearDown() {
		if(driver!=null) {
			System.out.println("Closing chrome browser");
			driver.quit();
		}
	}
 
}

In the above example class 'ChromeExample' is accessing the method 'getDriver()' from the class Browser. If we have not declared Browser class as public, we will get compile time error as ‘The type com.easy.Browser is not visible in the class’.

If the method ‘getDriver()’ is defined with private modifier and when we try to access that method from class ‘ChromeExample’, we will get compile time error as ‘The method 'getDriver(String)' from the type Browser is not visible’.

Private Access Modifier

If a method or variable is declared as private, it can be accessible only within the same class. Private modifier is not accessible outside the class in same package or from other packages. Even the child classes also unable to access private methods.

For classes, if a class is declared as private the class cannot be accessible from other classes. Private method is applicable only for inner classes. Mostly private modifier is used for methods and variables.

We can declare all members and methods as private, but they are much useless, since we can't access any of them from another class except its own class. We should limit the accessibility to private as possible.

Example:

package se.javamodifiers;

public class PrivateDemo {
	private int b=20;
	private void method1(){
		System.out.println(b);
		
	}
	
	public static void main(String[] args) {
		PrivateDemo pd= new PrivateDemo();
		pd.method1();
	
	}

}

If we try to access from other class we get compile time error saying "The method method1() from the type PrivateDemo is not visible"

package se.javamodifiers;
public class PrivateDemo {
	private int b=20;
	private void method1(){
		System.out.println(b);
	}
	
	public static void main(String[] args) {
		PrivateDemo pd= new PrivateDemo();
		pd.method1();
	}
}
class Test {
	public static void main(String[] args) {
	PrivateDemo pd= new PrivateDemo();
	pd.method1();// Here we cannot access private method
}
}

Let us look an example for Private access Modifier using Selenium webdriver

In the above example, class ‘Browser.java’ has a private string variable ‘driverPath’ which is only accessed within the class. Basically we don't need this variable to be accessed by other classes, hence we have declared ‘driverPath’ with private modifier.

private String driverPath = "F:/chromedriver/";

And as discussed above, If we declare private modifier for method ‘getDriver()’, then when we access method from class ‘ChromeExample’, we will get compile time error as ‘The method getDriver(String) from the type Browser is not visible’. And also, all the locators are defined with private modifiers as these are specific to this particular page. If you have seen Page Object Modal and Page Factory Pattern, we will define all the locators with private modifiers in selenium webdriver when we know that they are only accessed within that class.

Protected Access Modifier

If a method or variable is declared as protected, they can be accessible from any class within the package and child classes of other packages.

Example:

package se.javamodifiers;
public class ProtectedDemo {
	protected int p=10;
	
	protected void methodDemo(){
		System.out.println("This is Protected Modifier Method" +p);
		
	}
}
class Demo {
	public static void main(String[] args) {
	    ProtectedDemo pd= new ProtectedDemo();
	    pd.methodDemo();
	    System.out.println(pd.p);
	}
}

The above example is class ProtectedDemo variable and method is declared with protected. Now this members can be accessible from any other class which is present in same package. As Demo class and ProtectedDemo class are in same package it can be accessible.

now we will see how to access protected member from child classes of other packages. Whenever a method or variable is protected in parent class and the child class which is present in other package must access with child class reference only. it cannot be accessible with parent class reference.

Example 2:

package se.javafundamentals;

import se.javamodifiers.ProtectedDemo;

public class Child extends ProtectedDemo{
	public static void main(String[] args) {
		// Here we will try to access method1() which is present in Protected class by using ProtectedDemo reference.
	/*ProtectedDemo pd= new ProtectedDemo(); ----> line 1
	pd.methodDemo(); ---->line 2*/
		
		Child cd= new Child();
		cd.methodDemo();
		System.out.println("Accessing Parent method in Child which is declared as protected:  " +cd.p);
	
    }
}

In the above example if we un-comment line 1 and 2 we get compile time error saying "The method methodDemo() from the type ProtectedDemo is not visible"

But in the case of classes parent and child which are present in same package and the parent class is declared with protected members then, these members can be accessible with either parent reference or with child reference.

Java Tutorials for Selenium: 

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.