encapsulation_java
encapsulation_java
Projects: A Comprehensive
Beginner's Guide
When learning Java Selenium, understanding object-oriented programming concepts is
essential. Encapsulation is one of these foundational concepts. In this post, we’ll explore
encapsulation in depth, how it is applied in Java Selenium, and its role in building robust
automation frameworks. By the end, you’ll also see an example of a real-world Selenium
framework demonstrating encapsulation in action.
What is Encapsulation?
Encapsulation is the process of wrapping data (variables) and methods (functions) into a
single unit, typically a class. In simpler terms, it’s about controlling access to the inner
workings of a class while exposing only what is necessary.
Encapsulation helps:
● Safe Deposit Locker: Imagine you have a safe deposit locker at a bank. Only you (or
someone you authorize) can access it using a key. The locker is like a class, the
contents are private data, and the key is a method to access it.
● Car Controls: You use a steering wheel, accelerator, and brakes (public methods) to
control the car, without needing to know how the engine or transmission works
(private implementation).
Encapsulation in Java Selenium
Basic Example
// Constructor
public User(String username, String password) {
this.username = username;
this.password = password;
}
// Getters
public String getUsername() {
return username;
}
1. Private Variables:
○ The username and password variables are declared as private to ensure that
they are not accessible directly from outside the class.
○ This enforces encapsulation, as external classes cannot modify these
variables directly.
2. Constructor Initialization:
Now, let’s see how encapsulation is applied in the Page Object Model (POM), a common
design pattern in Selenium.
// Encapsulation in a Login Page
public class LoginPage {
private WebDriver driver;
1. Private Locators:
Let’s create a sample framework for an e-commerce website. The framework will:
Step 1: ConfigurationManager
public class ConfigurationManager {
private static final String BASE_URL = "https://ecommerce.com";
private static final String BROWSER = "chrome";
1. Private Variables:
○ The BASE_URL and BROWSER variables are declared as private static final,
meaning their values cannot be changed once set.
○ These variables are encapsulated within the ConfigurationManager class to
provide controlled access.
2. Public Getters:
○ Other test scripts can access configuration details (like the base URL or
browser type) via the ConfigurationManager.getBaseUrl() and
ConfigurationManager.getBrowser() methods, ensuring encapsulation
principles are maintained.
1. Private Locators:
driver.quit();
}
}
Step-by-Step Code Execution for SearchTest:
1. Driver Initialization:
○ The browser is closed using driver.quit(), ensuring that the test session is
properly cleaned up.