Why syntax is “driver.manage().window().maximize();”?

Hello Folks,

In my last post, I explained about some useful methods of WebDriver. I got some comments to explain why do we write syntax as below:

Actually it’s JAVA concept. It is called as method chaining. We will learn about this now.

Some basic Concepts of JAVA:
1. There can be two types of members in a java class. Static and Non-static.
2. Static methods can be called using class name or by creating an object of that class but calling by class name is perfect practice.
3. Non-static members of class can be called only through object of class.
4. A method can return a type. It may be class or interface as well.

#JAVACODE to learn how to call static and non-static methods:

Outout:
static method
Non static method
static method

#JavaCode to understand method chaining:

Explanation:
1. There are total three classes “Demo”, “AnotherDemo” and “NewDemo”.
2. Class “Demo” has a method “DemoMethod” which return an object of class “AnotherDemo”.
3. Class “AnotherDemo” has a method “AnotherDemoMethod” which return an object of class “NewDemo”.
4. Class “NewDemo” has a method “NewDemoMethod” which return void.
5. Only class “Demo” has main method and through that method we want to access “NewDemoMethod” of class “NewDemo”.
6. We created an object of “Demo” to access method present in class “Demo”.

Demo DemoObject= new Demo();
7. Now, we will call “DemoMethod” of class “Demo” which returns an object of class “AnotherDemo”, which we can store in a variable of type “AnotherDemo”.

8. Now what we have?? An object of class “AnotherDemo” means we can access methods of class “AnotherDemo”.
9. We call method “AnotherDemoMethod1” of class “AnotherDemo” which returns an object of class “NewDemo”, which we can store in a variable of type “NewDemo”.
NewDemo NewDemoObject= AnotherDemoObject.AnotherDemoMethod();

10. Now, we can access method of “NewDemo”.
NewDemoObject.NewDemoMethod();

11. So, now we have following lines of code:

12. Now, refer the below image:
IMG_8376
13. Above code has concepts of method chaining and anonymous object. When we need to use object once in a program, we can go for anonymous object for better memory utilization.

I hope above java concept must be clear.
Same logic is applied for selenium. I will explain one statement:
driver.manage().window().maximize();

When we call manage() method, it returns a “Options” type. “Options” is an interface.

Interface “Options” has method “windows” which returns “Window” type.

Now, we can use any method of interface “Window”. it has following methods which can be called.

See complete code below:

That’s it. I hope you must have learnt new thing. If still you have doubt,feel free to comment or do email.
I strongly believe when you know answer of both “how” and “Why”, you can write better scripts.

#HappyLearning
#Thanks

Author: Amod Mahajan