OOPS in Java

Object means a real-world entity such as a pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects.

It simplifies the software development and maintenance by providing some concepts:

  1. Object
  2. Class
  3. Inheritance
  4. Polymorphism
  5. Abstraction
  6. Encapsulation

Classes in Java

A class is a user defined blueprint or prototype from which objects are created. It represents the set of variable and methods that are common to all objects of one type.

Modifiers : A class can be public or has default access

Class name : The name should begin with a alphabets and most of the time we follow CamelCase convention, First letter of all the words are in Upper case.

Superclass : Like everyone in the real word, even Java classes can have parents, these parents are called as Superclass, Any given Class can have only one class as Parent.( Donot ask whether it is mother of father)

Interfaces : Interfaces are empty containers which sets the rules for other interfaces and for classes.

Body : A class body is contained within curly braces { }, class can contains methods, variable, inner classes, constructors, static blocks, default blocks

Object : As everyone says, it is like real object in our world, But Objects are nothing but the container of the non-static elements in the class, Objects will have value, address

Object Creation

We can create object for any class in Java, to create we will use most preferred way. i.e with new key word.


								Type variable = new constructor();
								A objA = new A();
								


Type is nothing but the type of the object

variable is nothing but any name for the object

new is the keyword to reserve the memory space on the stack

Constructor is the one which will loads all the non-static elements in the class into space that reserved by the new keyword, Constructor name is same as Class name

We can access all non-static members of the class via object reference with dot operator.


								public class A {
									public void test() {
										System.out.println("test method");
									}
									public static void main(String[] args) {
										A objA = new A();
										objA.test();
									}
								}			
								

Constructors in Java

Constructor is a block of code that allows you to create an object of class. This can also be called creating an instance.

Constructor looks like a method but it’s not, for example methods can have any return type or no return type but constructors don’t have any return type not even void.

Constructor has following properties:

  • Constructor has same name as class name.
  • It is used for initializing variables of class..
  • It is called whenever object of class is created..
  • It does not have return type, not even void..
  • It can have parameter.
  • Constructors can be overloaded, which means a class can have more than one constructor.
  • Overriding doesnot applicable for constructor, as the overriding occurs on inheritance with different classes..
  • A constructor may have any access modifier like private, protected, default, public..
  • Default constructor is automatically inserted when Compiler does not find any valid declaration of a constructor inside a class..
Types of Constructor:
  1. Default Constructor
  2. No-Param construtor
  3. Parameterized Constructor
  4. Copy Constructor

Default Constructor :

Default Constructors will not accept any parameters; default constructor is created during the compile time.

Default constructor will be created only in case of when user doesnot provide a constructor.

Why do we need default constructor ? At the beginning of an object's life, the Java virtual machine (JVM) allocates memory on the heap to accommodate the object's instance variables.

When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable.

To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values before it is used by any code.

The default constructor assigns the default values to the non-static elements present in the class

In below example there is no constructor an default constructor will be formed by the constructor, as like everyone I also think that default constructor may look like No-Param constructor


								public class A {
									public void test() {
										System.out.println("test method");
									}
									public static void main(String[] args) {
										A objA = new A();
										objA.test();
									}
								}			
								

Default Constructor in Selenium:

Selenium browser classes (FirefoxDriver, ChromeDriver) has param and no-param constructors so which makes that there is no default constructor present in selenium.

No-Param constructor :

No-param constructor is nothing but a constructor without any parameters, Once a constructor is present in the class then compiles will not create a constructor.


public class A {
	// no param constructor
	public A() {
		// constructor block
	}
	public void test() {
		System.out.println("test method");
	}
	public static void main(String[] args) {
		A objA = new A();
		objA.test();
	}
}			

No-Param constructor in Selenium:

Selenium has few no-Param constructors in its package, below are the few no-param constructors present in selenium.

  • new FirefoxDriver(); // chrome as well
  • new Properties()

Parameterized Constructor :

A constructor having parameter is called parameterized constructor, parameterized constructor can have any number of parameters and any type of parameters.


						public class B {
							// no param constructor
							public B(int i, boolean flag) {
								System.out.println("Parameterized constructor");
							}
							public void test() {
								System.out.println("test method");
							}
							public static void main(String[] args) {
								B objA = new B(10, false);
								objA.test();
							}
						}			
						

Parameterized Constructor in Selenium:

Browser Classes in selenium accepts the .exe file location of the browser, when browser is not installed in standard path, these will accept the file path or the Binary path as parameter and these are example for parameterized constructors.

Select class and Actions class constrctors also accepts parameter in the form of Webelement and WebDriver respectively

  • new FirefoxDriver(Capabilities desiredCapabilities)
  • new ChromeDriver(ChromeOptions options)
  • new Select(WebElement element)
  • new Actions(WebDriver driver)

Copy Constructor :

As the name suggests it create a copy of the constructor, A copy constructor is a constructor that takes only one argument which is of the type as the class in which the copy constructor is implemented.

For example, let us assume a class namely Animal and it has a constructor called copy constructor which accepts only one argument and that too type of Animal.

Copy constructors are widely used for creating duplicates of objects known as cloned objects. Duplicate object in the sense the object will have the same characteristics of the original object from which duplicate object is created.

But we have to ensure that both original and duplicate objects refer to different memory locations

So we are free to use copy constructors instead of clone method in java, but recommended is clone method.


class Foo {
	public int x;
	public int y;
 
	// Sample constructor
	Foo(int x, int y) {
		this.x = x;
		this.y = y;
	}
	// Copy constructor
	Foo(Foo foo) {
		this.x = foo.x;
		this.y = foo.y;
	}
}
public class AD {
	public static void main(String[] args) {
		Foo fooA = new Foo(3, 5);   // initialize foo1
		Foo fooB = new Foo(fooA);  // copy foo1 to foo2
		fooB.x = 7;
		fooB.y = 8;
		System.out.println(fooA.x + " " + fooA.y); // prints "3 5"
		System.out.println(fooB.x + " " + fooB.y); // prints "7 8"
	}
}			

Copy Constructor in Selenium :

Selenium donot have any classes which support copy-constructor

Constructor Overloading :

Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters.

Constructor overloading is not much different than method overloading. In case of method overloading you have multiple methods with same name but different signature, whereas in Constructor overloading you will have multiple constructor with different signature.

Benefit of Constructor overloading : Benefit of having constructor overloading is Backward/Forward Compatibility. Say after sometime you decide that Employee class is going to have one more property "age", along with the existing name.

Now what you do, If you change the parameterized constructor than you will have to change at all the places where you have used it.

So to make sure that your class is adapting to the new changes while keeping the old standards intact you create a new parameterized constructor with 2 parameters.

So now you have two constructors with completely different and valid purpose.


class Employee {
	public Employee(String empName) {
		System.out.println("constructor with name");
	}
	public Employee(String empName, int age) {
		System.out.println("constructor with name and age");
	}
}

public class EmployeeTest {
	public static void main(String[] args) {
		Employee emp = new Employee("karthiQ");
		Employee emp1 = new Employee("Tom", 28);
	}
}			

Constructor overloading in Selenium

We have constructor overloading in selenium as well, In selenium the when we open a browser we would be callig the constructors of FirefoxDriver class, ChromeDriver class, etc.

These browser driver classes has the overloaded constructors, but most of the time what we use is FirefoxDriver, ChromeDriver, there are other constructor which accept the parameter of different type

Few of the overloaded constructor are below : 1. Browser driver constructors :


// firefox
new FirefoxDriver()
new FirefoxDriver(Capabilities desiredCapabilities)
new FirefoxDriver(FirefoxOptions options)
// chrome
new ChromeDriver()
new ChromeDriver(Capabilities desiredCapabilities)
new ChromeDriver(ChromeOptions options)			


2. Actions class constructors


new Actions(Keyboard keyboard)
new Actions(WebDriver driver)			

Constructor Calling Constructor

We can call one Constructor from other constructor with help of the this() method in java, this method always should be the first line in the Constructor.


public class K {
	public K() {
		this(10);
		System.out.println("No param constructor");
	}
	public K(int i) {
		System.out.println("Parameterized Constructor");
	}
	
	public static void main(String[] args) {
		K objK = new K();
	}
}			

Output of constructor calling constructor


Parameterized Constructor
No param constructor			

Inheritance in Java

Inheritance is the process where the characteristics are inherited from ancestors (super classes). Inheritance in java can be defined as a mechanism where a new class (subclass) is derived from an existing class(super class) properties.

It is possible for classes to inherit or acquire the properties and methods of other classes, just like a son can acquire some traits and behavior from his father.

In Java inheritance is declared using the extends keyword. You can declare that one class extends another class by using the keyword extends in the class definition


extends keyword used for Class to Class relationship.
extends keyword used for interface to interface relationship
implements keyword used with Interface to class interface

Child Class / Sub Class : The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class / Super class : The class whose properties and functionalities are used(inherited) by another class is known as parent class, super class or Base class.

Important things in Inheritance

  • Most important benefit of inheritance is code reuse because subclasses inherit the variables and methods of superclass.
  • Private members of superclass are not directly accessible to subclass, as private members' scope is only the particular class where they are declared.
  • Superclass members with default access is accessible to subclass only if they are in same package,. Default access is nothing but the state where you donot specify Public, Private, Protected.
  • Constructors are not inherited by subclasses.
  • We can override the method of Superclass in the Subclass, this most important when you inherit a interface
  • If a class is Final then we cannot inherit that class.

Types of inheritance :

There are four types of inheritance in java, those are :

  1. Single Inheritance
  2. Multi-level Inheritance
  3. Multiple Inheritance
  4. Hybrid Inheritance

Single Inheritance :

When a single child class inherits the properties of a parent class, it is known as single inheritance. There are no other child classes present for that parent class. single-inheritance-java


package cherchertech;

class BaseClass {
	public void testa() {
		System.out.println("test a");
	}
	public void testb() {
		System.out.println("test b");
	}
}

class ChildClass extends BaseClass{
	public void testc() {
		System.out.println("test c");
	}
}

public class SingleInheritance {
	public static void main(String[] args) {
		ChildClass cc = new ChildClass();
		// methods present in base class
		cc.testa();
		cc.testb();
		// method present in child class
		cc.testc();
	}
}
			
single-inheritance-java-output

Single inheritance in Selenium :

There are few class which are having single inheritance in selenium webdriver

I have considered the Object class while writing these classes as example for single inheritance in selenium.

Few example for single inheritance in selenium webdriver :

  • 1. Point Class
  • 2. Dimension class
  • 3. FirefoxBinary class
  • 4. FirefoxProfile class
  • 5. Rectangle class
  • 6. Json class

From below image you can understand that FirefoxBinary class extends Object class and FirefoxBinary class will have all its own methods along with inherited Object class methods.

By default if you write any class in java without writing any extends, still the single inheritance is applicable for it because all the classes in java are inherited from Object class.

selenium-single-inheritance-java

Multi-level Inheritance :

When a class extends a class, which extends another class then it is called multilevel inheritance.

Multilevel inheritance is nothing but the combination of more than one single inheritance

In multiple inheritance you have one path only to reach the highest class in the inheritance.

Minimum three classes are required to achieve the Multi-level inheritance in java.


The last sub class will have all the properties present in its super classes.

In below example you have only one path to reach from last sub class to top most class, Grand child class -> Child Class -> Base class


package cherchertech;

class BaseClass {
	public void testa() {
		System.out.println("Base class test");
	}
}

class ChildClass extends BaseClass{
	public void testb() {
		System.out.println("Child class test");
	}
}
class GrandChildClass extends ChildClass{
	public void testc() {
		System.out.println("Grand child class");
	}
}

public class MultiLevelInheritance {
	public static void main(String[] args) {
		GrandChildClass gc = new GrandChildClass();
		// method present in base class
		gc.testa();
		// method present in child class
		gc.testb();
		// method present in grand child class
		gc.testc();
	}
}
			
multilevel-inheritance-java

Multi-level Inheritance in Selenium

TouchActions in selenium works on the principle of Multi-level Inheritance, TouchActions class extends the Actions class and Actions class extends the Object class in selenium.

Touch Actions class will have all the methods present in the Object class and Actions class, I have mentioned only few method from each class because of space constraint

multilevel-inheritance-selenium

Multiple Inheritance :

Multiple inheritance is nothing but a class/interface is inheriting the properties of more than one class or interface.

A class cannot inherit the more than one class because it forms multiple paths to reach the top most class from the same last sub class.

This is where you need to remember that all the classes in java are subclasses to Object class.

So Multiple inheritance is not possible when a class tries to inherit more than one class, if class tries so, then it creates a diamond problem.

But a class can inherit one class and implement multiple interfaces and this is also called as multiple inheritance.

Similar to this Interfaces also can inherit from more than one interface, java allows multiple inheritance only because interfaces will not have any implementations

multple-inheritance-java

Multiple inheritance in Selenium :

In selenium, ChromeDriver extends the RemoteWebdriver, RemoteWebdriver implements Webdriver and extends Object class. RemoteWebdriver follows Multiple-inheritance as it use methods from Object class and also overrides the methods present in the Webdriver by implementing them

multile-inheritance-selenium

Hybrid Inheritance :

Hybrid inheritance is the combination of every type of inheritance that exist. As java doesn't support multiple inheritance, hybrid inheritance also can't be implemented.

If you consider the above definition then Hybrid inheritance is not possible

For most of the java people the Hybrid inheritance definition is : Combination of Single level and Multilevel inheritance.

Other way of saying : When two classes inherit properties from a single class then it is called Hybrid inheritance.

hybrid-inheritance-java


package cherchertech;

class BaseClass {
	public void testa() {
		System.out.println("Base class test");
	}
}

class Child_1_Class extends BaseClass{
	public void testb() {
		System.out.println("Child 1 class test");
	}
}
class Child_2_Class extends BaseClass{
	public void testd() {
		System.out.println("Child 2 class test");
	}
}
class GrandChildClass extends Child_1_Class{
	public void testc() {
		System.out.println("Grand child class test");
	}
}

public class HybridInheritance {
	public static void main(String[] args) {
		GrandChildClass gc = new GrandChildClass();
		// method present in base class
		gc.testa();
		// method present in child 1 class
		gc.testb();
		// method present in grand child class
		gc.testc();
		
		// create object child class 2
		Child_2_Class c2c = new Child_2_Class();
		// method present in child 2 class
		c2c.testd();
	}
}
			
hybrid-inheritance-output-java

Hybrid Inheritance in Selenium :

ChromeDriver class is the example for the Hybrid inheritance, ChromeDriver is inherited from the RemoteWedriver and RemoteWebdriver is inherited from the Object class this is one path and this is nothing but Multi-level Inheritance.

In another path ChromeDiver extends RemoteWebdriver, and RemoteWebdriver also implements Webdriver interface

FirefoxBinary class extends the Object class this is third path also called Single-Inheritance.

RemoteWebdriver follows multiple inheritance by implementing Webdriver and by extending Object class.
hybrid-inheritance-selenium

Diamond problem and Why Java Does not have it :


diamond-problem-multiple-inheritance-java

The above image shows the diamond problem, let me explain the problem.

1. Class A extends Object class
2. Class B extends Object class
3. Class C extends Class A and class B.
4. Object class has methods called toString().
5. The relation between class C and classes A, B is Multiple inheritance
5. Classes A, B, C have method toString(), because they inherit the Object class

Lets create object for class C and call the toString() method, which indrectly gives call to toString() method present in the Object class.

Now take moment and think, In how many ways we can reach the Object class from the class C, yes Your are right, in two ways we can reach it.

1. Class C -> Class A -> Object class
2. Class C -> Class B -> Object class

Take a moment and think which is the way you are gonna use, Path 1 or Path 2 (consider you donot know the consequences of the path, good or bad).

Are you able to come to conclusion ? No, okay now the same thing happens with the Programming language as well, it gets confused which path to choose like Mr.Nobody movie, the Programming language will throw an exception of ambiguity.

To avoid this java Programming language author a made decision not to include the multiple inheritance. So we donot have Multiple inheritance between the classes.

In My language : There are two section of school students, among them each section has a student with roll number 1224, If principal asks an attender to call a guy (one guy) with roll number 1224, whom does that attender will call ?, he cannot call any body as there are two guys with same roll number, unless he is stupid like me.

Upcasting :

Upcasting is casting a subtype to a supertype, upward to the inheritance tree. In other words, Making a child or grand child as the grand father.

While creating a Object to a child class we will write Parent class type as the type for the object.

We can mention the the type to which '(A)' we are going to Upcast the object.


A a = (A) new B(); // where B is sub class of A			

Once we upcast the sub class then only methods from the Super class is available for that object.

But if a sub class has any method which is same as Superclass method then super class method will be overridden by the sub class and sub-class method implementation only will work.


class A {
	public void test(){
		System.out.println("test A");
	}
	public void subtract(){
		System.out.println("subtract A");
	}
}
class B extends A{
	public void test(){
		System.out.println("test B");
	}
	public void add(){
		System.out.println("add B");
	}
}
public class C {
	public static void main(String[] args) {
		A a =(A) new B();
		a.subtract();
		a.test();
	}
}			

Output of the up-casting program


subtract A
test B			

We donot have subclass method in suggestions as well. upcasting-java

Auto-Upcasting :

Auto-upcasting is nothing but the upcasting occurs automatically by the compiler, we can write the above example's object creation like below


A a = new B();			

Auto - Upcasting in Selenium :

I hope you know where auto-upcasting occurs in selenium webdriver, If you are not aware of it then auto-upcasting occurs in first line of the webdriver code.


WebDriver babyDriver = new FirefoxDriver();			

In above example we are assigning the lower level class object to upper level class/interface type.

WebDriver is Interface and FirefoxDriver class extends the Webdriver interface, so in above example we are assigning the FirefoxDriver Object to Webdriver type.

auto-upcasting-selenium

Down casting

Down casting is nothing but converting the sub class type which is upcasted to Super class into sub class type, instead of performing the down casting we can directly create the object to sub class.

For creating a down casting process, Upcasting is mandatory.

For above Upcasting example:


A a = new B(); // auto-upcasting
B b =(B) new B(); // downcasting

"Donot you think instead of writing above two steps, we can write like below"
B b = new B();		

Polymorphism in Java

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

We can create functions or reference variables which behave differently in different programmatic context.

Polymorphism is one of the major building blocks of object oriented programming along with inheritance, abstraction and encapsulation.

There are two kinds of polymorphism in java :
1. Compile Time polymorphism / Static polymorphism
2. Run Time Polymorphism / Dynamic Polymorphism

Method Overloading :

Method Overloading is a feature that allows a class to have more than one method having the same name, with different type of parameters or with different number of parameter or both.

Things to remember on method Overloading

  • To call an overloaded method in Java, it is must to use the type and/or number of arguments to determine which version of the overloaded method to actually call.
  • Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method.
  • When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
  • It allows the user to achieve compile time polymorphism.
  • An overloaded method can throw different exceptions.
  • It can have different access modifiers.

class OverloadExample
{
	void demo (int a)
	{
	   System.out.println ("a: " + a);
	}
	void demo (int a, int b)
	{
	   System.out.println ("a and b: " + a + "," + b);
	}
	double demo(double a) {
	   System.out.println("double a: " + a);
	   return a*a;
	}
}
class OverloadingMainClass
{
	public static void main (String args [])
	{
		// create object for OverloadExample
		OverloadExample Obj = new OverloadExample();
		Obj.demo(10);
		Obj.demo(10, 20);
		double result = Obj.demo(5.5);
		System.out.println("Output : " + result);
	}
}			

Rules for Method Overloading

1. Overloading can take place in the same class only, it would be considered as different method if the overloading is happening in its sub-class.

2. Constructor in Java can be overloaded same as Method

3. Overloaded methods must have a different argument list. The parameters may differ in their type or number, or in both.

4. They may have the same or different return types.

5. It is also known as compile time polymorphism.

Method Overloading in Selenium :

Selenium uses method overloading to accept different parameters, without disturbing the other methods.

I hope you are familiar with Frames, How do you switch a frame in selenium ?
You will use driver.switchTo().frame(String id or Name), frame(Webelement element, Did you notice both the methods names are same but they accept different types of parameter.

First frame(String id or Name) accepts a String parameter, but second frame(WebElement element) accepts the Webelement as parameter.

When there is more than one method with same name and those methods accepts either different types of parameter or different number parameter then it is called as Method Overriding.

There are few more places in selenium where method overriding is implemented, Those are :
1. Methods present in Actions class, Method accepts webelement , and another method accepts no parameter, few methods accepts co-rodinates with webelement
method-overriding-selenium-actions

2. Almost all the methods pressent in the Assert class in TestNG. method-overloading-selenium-assert

Type Casting in Method Overloading :

Changing the type of an value from one primitive type to another primitive type is called as Types casting. Mostly typecasting occurs with the types whose parent is Number class.

When a data type of smaller size is promoted to the data type of bigger size than this is called Widening

If Bigger size is converted to lower size then it is called as Narrowing. There is no auto-narrowing, which means compiler cannot narrow values unless user specifies so.

If we donot specify the type conversion explicitly then compiler itself will perform the widening operation and this is called Auto-Widening.

For example: byte data type can be promoted to short, a short data type can be promoted to int, long, double etc.

Type Casting can occur towards bigger size, or to lower size as well

type-casting-diagram

Example for widening and Auto-widening, and Narrowing


int i = 10;
// widening
float f = (float) i;
// auto widening
float fAuto = i;

// narrarowing
double doub =  10.12;
int inarrow = (int) doub;			

Not only in normal scenarios the type casting occurs but in case of method overloading also the type casting occurs, but mostly Auto-widening and also called as TypePromotion

Type casting will not occur in method overloading if there is a method with exact matching signature

More than one method with same name and argument list cannot be given in a class even though their return type is different, Method return type doesn’t matter in case of overloading.


package cherchertech;

public class TypeCastingExample {
	// method with byte inputs
	public void add(byte b1, byte b2)
	{
		System.out.println("BYTE addition result is : " + (b1+b2));
	}
	// method with int inputs
	public void add(float f1, float f2)
	{
		System.out.println("FLOAT addition result is : " + (f1+f2));
	}
	
	public static void main(String[] args) {
		// we will call the add method with int values
		//there is no method which accepts int values
		TypeCastingExample te = new TypeCastingExample();
		int a = 10, b = 10;
		te.add(a, b);
	}
}
		
Can we overload java main() method?

You can have n - number of main methods in a class by method overloading. But JVM calls main(String[] args) method which receives string array as argument only.


package newtest;

public class MainMethodOverloading {
	public static void main(String[] args) {
		System.out.println("String args main");
	}
	public static void main(int i) {
		System.out.println("int main");
	}
	public static void main(int i1, int i2) {
		System.out.println("two int main");
	}
	public static void main(boolean b) {
		System.out.println("boolean main");
	}
}
			
output of main method overloading : main-method-overloading-java

Reading QR Code from website using Webdriver

Method Overridding

Sub class has the same method as of Super class. In such cases Sub class overrides the parent class method without even touching the source code of the Super class. This feature is known as method overriding.

The Sub class will provide the implementation as per its wish, Parent class will not have any control on how to implement the method.

Method Overridding is also known as Runtime polymorphism.

public class BaseClass
{
	public void methodToOverride() //Super class method
	{
		 System.out.println ("I'm the method of BaseClass");
	}
}
public class DerivedClass extends BaseClass
{
	public void methodToOverride() //Sub Class method
	{
		 System.out.println ("I'm the method of DerivedClass");
	}
}
 
public class TestMethod
{
	 public static void main (String args []) {
		// BaseClass reference and object
		BaseClass obj1 = new BaseClass(); 
		// BaseClass reference but DerivedClass object
		BaseClass obj2 = new DerivedClass(); 
		// Calls the method from BaseClass class
		obj1.methodToOverride(); 
		//Calls the method from DerivedClass class
		obj2.methodToOverride(); 
	 }
}			

Rules for Method Overriding :

1. Applies only to inherited methods

2. Object type (NOT reference variable type) determines which overridden method will be used at runtime

3. Overriding method can have different return type.

4. Overriding method must not have more restrictive access modifier

5. Abstract methods must be overridden

6. Static and final methods cannot be overridden

7. Constructors cannot be overridden

Dynamic method dispatch in overridding :

Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime.

When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to.

In simple words, You have a grandfather and brother and sister. All of you grand children have inherited your grand father behaviors along with your own behaviors.

Now can I create a method which accepts your Grand father behaviors, the same method can accept you ( any of your sibling) because you are his grand-children.

If I pass you grand father as parameter then method behaves based on your grand father characters, but if I pass you as parameter then you will exhibit your + your grand father characteristics.

So this method is not locked with your grand-father or with your sibling, but it behaves based on the parameter you pass. So the coupling between the method and the caller happens only during the runtime, this is called as dynamic dispatching.

If you have heard of Multiple personality dis-order in real world.

In below example the compiler cannot decide the coupling as the parameter are resolve at run time, so dynamic dispatching or runtime coupling occurs.

Sorry for the below example, just yesterday I watched the 'Avengers : Infinity War 1'.


package newtest;

class SuperHero {
	public void protection(GrandFather_Avenger hero) {
		hero.tool();
	}
}
class GrandFather_Avenger {
	public void tool() {
		System.out.println("All Tools of Avengers");
	}
}
class Child_Hulk extends GrandFather_Avenger{
	public void tool() {
		System.out.println("Size is tool for Hulk");
	}
}
class Child_Strange extends GrandFather_Avenger{
	public void tool() {
		System.out.println("Time is tools for Dr.Strange");
	}
}
class Child_TomCruise extends GrandFather_Avenger{
	public void tool() {
		System.out.println("Trust me !, I'm also super Hero, Didn't you watch 'MI rogue nation'");
	}
}
public class TestDynamicDispatching {
	public static void main(String[] args) {
		SuperHero sh = new SuperHero();
		// Hulk characteristics
		sh.protection(new Child_Hulk());
		// Dr.Strange characteristics
		sh.protection(new Child_Strange());
		// Tom Cruise characteristics
		sh.protection(new Child_TomCruise());
		// Avenger characteristics
		sh.protection(new GrandFather_Avenger());
	}

}
			

Abstraction in Java

Okay Guys, Forgive me for the information I am about to talk, because I am not able to accept the descriptions present in the Internet about the Abstraction.

Internet Says (almost all websites) : Hiding internal details and showing functionality is known as abstraction., I donot Agree with this because this is what Encapsulation. isn't it ?

I could be wrong in my description, but I will continue with my perception, if you are not comfortable please skip this topic

Abstraction is nothing but the process of giving an set of guidelines to the user, who are going to implement these guidelines based on their needs.

For Example : I hope you are aware of headphone jack in the phones and radios, or the different chargers for different mobiles, which were available till 2008 (approximately, i donot know the exact year). Previously we had different phones with different chargers and different headphones jacks

After 2008 most of he companies came to an agreement that everyone should manufacture the Phones based on few specifications, which included headphone, charger ports(except Apple).

So they have concluded with 3.5mm jack and standard charger port, now you can interchangeable use the chargers and the headphones.

Like you can use samsung headphone with onePlus mobile

Similar to above scenarios when an architect design a framework, or a library or a software, he will give a specifications/guidelines.

If somebody want to take advantage of the framework/library they have to implement those specifications or guidelines.

Java provides Interface and Abstract class to achieve this abstraction.

Interface in Java :

Interface defines set of methods as a contract or as guidelines. The class that is implementing this interface must implement these functionalities in the concrete class.

An interface allows you to guarantee that certain methods exist and return the required types. When the compiler knows this, it can use that assumption to work with unknown classes as if they had certain known behavior.

The interfaces add value when you are building a larger system or a library.

Using references to interfaces instead of classes helps in minimizing the future changes as the user of an interface reference doesn't have to worry about the changes in the underlying concrete implementation.

Whenever there is interface there is Inheritance, as the class which change/ overrides the interface method must be subclass of Interface.

Webdriver interface provides few standard abstract methods to handle the webpages, So when some browser want to access Selenium method, then they have to implement the Webdriver interface and provide implementation to the methods present in the Webdriver interface

You must implement the all the abstract methods present in the interface but the behavior of the methods could be on your own way.


public interface WebDriver {
	// public- access modifier
	// void- return type
	// get - method name
	public void get(String url);
	public String getTitle();
}			

Below Class implements the WebDriver interface.


public class FireFoxDriver implements WebDriver{
	@Override
	public void get(String url) {
		System.out.println("Open webpage");
		// actual code differs, in get method
	}
	@Override
	public String getTitle() {
		System.out.println("Webpage title");
		// actual code differs, in getTite method
		return "title";
	}
}			

If you donot implement the methods present in the WebDriver class then Compiler shows error.

Abstract Class :

We use abstract classes when we know the methods, but we don’t know how they would be implemented.

There are very few instances where implementing an empty method in Java is a good idea. The reason is, if someone were using our class, they wouldn’t know they needed to provide an implementation.

When we mark the method as abstract, anyone using our class has no choice but to provide an implemented child class. They can’t instantiate the class otherwise.

This is called compile time safety. Compile-time safety ensures that any classes that extend our abstract class must provide the bare minimum functionality to work.

Then why cannot I use Interface instead of Abstract class, you cannot because if you want to provide implementation for few methods (concrete methods) then you must use Abstraction

Note : With latest updates of Interface, Abstract class may go obsolete in 3-4 years as Interface now started to accept the method with implementations.

Abstract method : method with no implementation

Concrete Method : method with implementation

We can override both abstract and concrete methods in subclasses, but we cannot create object to a abstract class, but we can create object to the subclass which overrides the abstract class completely.

Abstract class must have abstract keyword in method declaration so abstract methods.


public abstract class WebDriver {
	// public- access modifier
	// void- return type
	// get - method name
	public abstract void get(String url);
	public String getTitle() {
		System.out.println("Webpage title");
		// actual code differs, in getTite method
		return "title";
	}
}			

Below Class implements the WebDriver interface.


public class ABSFireFoxDriver extends WebDriver{
	@Override
	public void get(String url) {
		System.out.println("Open webpage");
		// actual code differs, in get method
	}
}			

Handling Custom Dropdowns in selenium

Multi-level Abstraction in Java :

It is not mandatory to override all the abstract methods present in the abstract class in single sub-class, if we donot provide all the implementation in subclass then we have to mark it as abstract class only.

We can create an object to a subclass which donot have any abstract methods in it. So we can implement the abstraction methods in multi-level

Multilevel Abstraction is nothing but the implementing a interface or Abstract class methods in different sub classes

For Example an Interface 'A' has 4 abstract methods called testa(), testb(), testc(), testd().

Now we can implements multilevel abstraction like class SubB implements interface A and provides implementation only to testa(), another class SubC extends SubB class and provides implementation to testb(), another class SubD extends SubC class and provides implementation to testc() and testd().

Now SubB, SubC classes are providing implementation to only few methods but not for all so they must be marked as abstarct classes. But class SubD provides implementation to all the methods so we can mark it as normal class and we can create object to it.

If you have query like SubD provides implementation to only testc(), testd(), then you might not notices the relation between the SubB, SubC, SubD.

When a parent class provides implementation to some abstract class then it is not mandatory for a subclass to provide implementation to the method, which has implementation in parent class

If you ask cannot I override it in subclass ?, yes you can override but it is optional only

Below images shows how the multi-level abstraction works: multi-level-abstraction-java

Program for multi-level abstraction


package test;
interface A{
	public void testa();
	public void testb();
	public void testc();
	public void testd();
}
abstract class SubB implements A {
	public void testa() {
		System.out.println("test-a");
	}
}
abstract class SubC extends SubB{
	public void testb() {
		System.out.println("test-b");
	}
}
public class SubD extends SubC{
	public void testc() {
		System.out.println("test-c");
	}
	public void testd() {
		System.out.println("test-d");
	}
	public static void main(String[] args) {
		// create object to class SubD
		SubD subdObj = new SubD();
		subdObj.testa();
		subdObj.testb();
		subdObj.testc();
		subdObj.testd();
	}
}


			
output-multi-level-abstraction

Encapsulation in Java :

Encapsulation is the process of binding/encapsulating the data and code together. It is used to hide the implementation details. The encapsulation can be achieved by the use of 3 keywords in java.

private : The variables or methods that have been declared as private will not be accessible outside the class, But same class member can access private methods and variables in class.

protected : The variable or methods that have been declared as protected will be accessible inside the class in which they have been defined and in the classes which extends this class. Protected Getter and Protected setter can be used to give access to only their family members

public : The variable or methods that have been declared as public will be accessible anywhere. Also, a class can be made public.

Mostly we use private and public methods for encapsulation, all the important details which we donot want to disclose to other member will be part of private method.

But somehow we want to let the user to know the result of the private method, so we will create a public method in a way that the method will show only the result of the private method to the user but not the implementation of the private method.

In case if we want to give more access to a same family member, inherited class then we create some protected methods which will give more details of the private method result which outside member of the family cannot see.

In my Language : Consider a organization as private method, employees as inherited class methods, General public or press as Outside members.

For every Quarter, organization releases a news letter stating the Profits/Losses to the press and employees, but same organization gives details about which project made what profit to the employees through the internal newsletter.

In below example we allow user to set and get the name of the employee using getter and setter, but we donot reveal any other details like how the name is processed and what are the operation happening to make up the emp name


package newtest;

class EncapsulationExample{
    private String empName;
    
    private void modifyEmpName(String newName) {
    	empName = newName + " : He acts in BigBang Theory";
    }
    public String getEmpName(){
        return empName;
    }
    public void setEmpName(String newName){
    	modifyEmpName(newName);  
    }
}
public class EncapsulationTest{
    public static void main(String args[]){
         EncapsulationExample obj = new EncapsulationExample();
         obj.setEmpName("Sheldon Cooper");
         System.out.println(obj.getEmpName());
    } 
}	
		
encapsulation-java

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Preety
    Such a good presentation skill u possess, keep it up
    Reply
    • karthiQ [ admin]
      Thanks Preety for the Pretty Words.
      My teacher used to say, i got the worst presentation skill in world :p
      Reply
  • Shri
    Fantastic article man, its hard to find OOPS concepts used in selenium tutorials. you nailed it, will be useful for many.
    Reply
    • karthiQ [ admin]
      Hi Shri,
      Thanks for the words, we are still adding few more concepts which will show  where we have used each and every piece of OOPS in Selenium. I would be adding them very soon
      
      Reply
  • Rahul
    Great topics and presentation. The topics present here has helped me a lot. Please add more Python-Selenium POM framework articles.
    Reply
    • karthiQ [ admin]
      Hi Rahul,
      
      Thanks For the  kind words, We are working on Python selenium tutorials.
      We would add POM in Selenium Python as soon as Possible.
      Reply
  • Copyright © CherCher Tech