abstraction in oop code example
Example 1: what is abstraction
it is process of hiding implementation details and
only showing the functionality to the user.
Abstraction focus on what the object does instead of how it does.
It is achieved by using Abstract class and Interface.
abstract methods (methods without body, cannot be static and final),
interface must implemented and abstract classes must be extended
by regular classes in order to achieve abstraction
(because abstract methods can only be exist in abstract class and interface).
A class can implement multiple interfaces,
but it can extend only single abstract class.
Ex: In my framework I have achieve abstraction by using collections or
Map, because it’s all interface. Most of the cases I come across using List.
If we want to access elements frequently by using index, List is a way to go.
ArrayList provides faster access if we know index.
If we want to store elements and want them to maintain an order,
List is a better choice.
i)List<String> webs=driver.getWindowHandles();
=>create a list first to store web URLs in list
ii)findElements evaluates multiple elements so therefore will assigned
to List <WebElement>
iii)To handle dynamic elements store it in the list and identify by index:
List<WebElement> all=driver.findElements(By.tagname(“”)); (or other locators).
Example 2: abstraction in oops
Abstraction is the concept of object-oriented programming that "shows" only essential attributes and "hides" unnecessary information.
The main purpose of abstraction is hiding the unnecessary details from the users.
It helps in reducing programming complexity and efforts.
Example 3: procedural abstraction examples
public void myFunction(String name) {
// whatever
}
public void myFunction(String name, boolean isAdult) {
// whatever, but now this is called whenever the extra parameter
// is callled instead of the other one
}
Example 4: where do you use abstraction in your framework
I used in defining a common super class while writing POM layer of the framework
We usually create an abstract class named
BasePage to have all common members for every page written
in this class like getPageTitle().
Then each Page class (HomePage, LoginPage, DashboardPage
etc.) inherit from BasePage.
Sometimes one may need to change the behavior of methods
implemented in superclass. So, subclass has freedom to
override that method where we use polymorphism.
This is how we use Abstract class in real projects