Table of Contents:



Software Quality Assurance (QA) TrainingJAVA BASICS FOR SELENIUM AUTOMATIONTable of Contents:Table of Contents TOC \o "1-3" \h \z \u Table of Contents: PAGEREF _Toc483394287 \h 2Revision History: PAGEREF _Toc483394288 \h 31.Java Introduction PAGEREF _Toc483394289 \h 42.Data Types PAGEREF _Toc483394290 \h 53.Loops PAGEREF _Toc483394291 \h 74.Arrays PAGEREF _Toc483394292 \h 85.Functions PAGEREF _Toc483394293 \h 116.Object Oriented Programming (OOP) PAGEREF _Toc483394294 \h 137.Static & Non-Static Functions PAGEREF _Toc483394295 \h 138.Difference between Object and Object References PAGEREF _Toc483394296 \h 159.Inheritance in Java PAGEREF _Toc483394297 \h 1610.Abstract Class: PAGEREF _Toc483394298 \h 2011.Overloading and Overriding Functions: PAGEREF _Toc483394299 \h 2212.Writing and Reading text files using Java PAGEREF _Toc483394300 \h 23Revision History:DescriptionVersionDateInitial version created1.04/13/16OOP chapter added2.04/19/16Added missing info in Java Intro and removed low priority info3.04/20/16Added Concept of Inheritance, Interface Overloadings and Overriding Functions,Example on inheritance,Object Class,Usage of Inheritance in Selenium4.04/22/16Writing and Reading text files using Java5.08/25/16Implementing Log4j API6.08/29/16Minor changes in one of the script7.03/9/17Added another script for Abstract class8.05/10/17Added OOP concepts24.08/2/2020Java IntroductionJava is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!. Java is open source (free to download /install) programming language and can develop and execute program on again platform (windows, unix/linux, mac etc) since it is a platform independent.Java Class: A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Example for Class is Login module.Java Method: A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console. Example for Method is Login Test Cases (Login with blank username/pwd, invalid un/pwd, valid un/pwd etc…).JAVA setup on Windows/Mac:Download/Install Java/JDK SE Development Kit 8u191Accept license agreementDownload (for Windows): Windows x64207.22 MB jdk-8u191-windows-x64.exeDownload (for Mac): Mac OS X x64245.92 MB jdk-8u191-macosx-x64.dmgCopy the downloaded .zip file to relevant location (ex: C:/Selenium/1119) and unzip it.How to check whether java is really installed on my computer:Open command promptType java -versionYou should see like below:Picked up JAVA_TOOL_OPTIONS: -Djava.vendor="Sun Microsystems, Inc"java version "1.8.0_251"Java(TM) SE Runtime Environment (build 1.8.0_251-b08)Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)Now setup Environment Variables with java/jdk paths: Setup the following environment variables in System and User variables:User variables:JAVA_HOMEC:\Program Files\Java\jdk1.8.0_191System variables:PathC:\Program Files\Java\jdk1.8.0_191\binRun the following commands on command prompt verify whether java/jdk setup done correctly: (you should not see any errors)java -versionjavac -version Eclipse setup on Windows OS:Install Eclipse: IDE for Java EE Developers 212 MB: Eclipse is an editor to develop java programs. Eclipse is the replacement for notepad or textpad.Check your laptop version (ex: Win7/8/10 32-bit or 64-bit by going to start—computer—right click properties)32-bit: : NEW eclipse folder (right click on .zip folder, extract here), open the extracted folder, go to eclipse folder, and double click eclipse.exe or right click on eclipse.exe-> create shortcut-> move it to task bar on the bottom of the desktop.Now double click on eclipse from task bar.Note/Error: If you see error message "Java was started but returned exit code=13" then uninstall 64 bit eclipse and install 32 bit ver of eclipse OR following this video to fix this issue: Windows 10, though it is 64 bit, please install 32 bit if you have an issue with 64 bitEclipse setup on Mac OS:Go to this link Eclipse IDE for Java EE DevelopersFollow below video to setup Eclipse on Mac OS. Workspace, Java project & Class in Eclipse: Open Eclipse -> Create workspace with the path: ex: C:\Selenium\0917\Java\JavaWS.File -> New -> Java Project (ex: JavaForSelenium) OR File -> New -> Project -> Java -> Java Project. SRC and JRE folders: JRE (java runtime environment) got installed when you install java on your system. Under SRC (source), you will develop all your java programs. Create a new class (ex: FirstJavaProgram) in SRC folder (right click src->new -> class) with checkbox “public static void main….” You must see 2files: .java file under /src folder and .class under /bin ment in java is // (for single line) and /* …………. */ (for multiple lines).Type below program:public class FirstJavaProgram {public static void main(String[] args) {System.out.println("Hello World");}} Run the java program (click run button or right click on .java program->run as -> java application)… you will see “Hello World” under the Console tab in eclipse.Note: To run java program, you can even use Cnt+F11 or Cnt+Alt+F11Go to source folder and look for bin/.class file: this is the executable file. Which can be executed on any OS since Java is a platform independent.Data Types Create new java class “JavaDataTypes”Update the script like below:// Java Data Typespublic class JavaDataTypes {public static void main(String[] args) {int i=10; //(in the memory of “i”, value 10 will be stored and should be numeric)long y=1234; // (it can also store integers like int but size of int is 32-bit whereas size of long is 64-bit. If you have very big number (6876787687), then use long instead of int. int and long cannot store decimal like 10.74 etc..)double z = 123.45; // (it can store integers and decimals .. both)char c = 's'; // (we can write only one char at a time inside char c)/* Note: Java offers 2 additional non-numeric primitive data types: char (to represent alphanumeric characters and special symbols) and boolean (to represent the truth values true and false) */boolean b = true; // (this can have only true or false values. Boolean will be used in conditional statements like IF/ELSE). String s = "hello world"; // String – something which can hold number of characters together – but it’s not a data type, it is an in-built class in java.System.out.println("Welcome to Java/Selenium");System.out.println(i);System.out.println(y); System.out.println(z); System.out.println(c); System.out.println(b); System.out.println(s); System.out.println(87); // if I run this, it will just print 87System.out.println(2>1); // if I run this, this will print trueSystem.out.println(2>3); // if I run this, this will print falseint a1=300;int b1=200;if (a1>b1){System.out.println ("a1 is the greatest " + a1);} else {System.out.println ("b1 is the greatest " + b1);}}}Run the script now (right click on script-> run as -> java application). You should see following output results:Welcome to Java/Selenium101234123.45struehello world87truefalseb1 is the greatest 200Comparison operators are: >, <, >=, <=, ==, !=Java Advanced Topics:Concatenation Operator – You can merge/concatenate/combine two Java String fields using the + operator.In Eclipse create a new class “JavaConcatenationOperator” with “public static void main ….” and type below code:public class JavaConcatenationOperator {public static void main(String[] args) {String s1 = "Selenium";String s2 = "Automation";System.out.println (s1+s2); // you will see “SeleniumAutomation”int a1 = 100;int a2 = 200;System.out.println (a1+a2); // you will see 300 System.out.println (s1+s2+(a1+a2)); // you will see Selenium Automation300}}Run the script now, you should see following results:Selenium Automation 300Selenium Automation 300Loops ****While Loop: The while statement continually executes a block of statements while a particular condition is true. Create a new class “JavaWhileLoop” with “public static void main ….” in Eclipse and write below code: // Print the numbers from 0-9public class JavaWhileLoop {public static void main(String[] args) {int i=0; // initialization while (i<10){ // conditionSystem.out.println(i);i=i+1; // increment / decrement}}}//Run: It will print numbers from 0 to 9Disadvantage of While Loop: If we don’t specify the condition (ex: i=i+1), then the loop will stuck infinitely (ex: it will print 0 infinitely) and cannot come out until you stop the execution manually (use terminate button in eclipse next to console tab).For Loop: The For statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. Create a new class “JavaForLoop” with “public static void main ….” in Eclipse and write below code:// Write a java code to Print first 10 numbers (0-9) and sum of 1st hundred numberspublic class JavaForLoop {public static void main(String[] args) {for (int i=0; i<10; i++) // i++ means i=i+1{System.out.println(i);} // this will print numbers from 0 to 9// Sum of first 100 numbersint sum=0;for (int n=0; n<=100; n++) { sum=sum+n;}System.out.println("Sum of first 100 numbers is " +sum); }}Where will we use For loop in Selenium? When we create data driven test in Selenium/WD/Java, multiple data (ex: username1/pwd1, username1/pwd2 etc) will read from excel sheet using For loop written in Selenium/WD/Java program.Arrays ****Single / One Dimensional Arrays An Array is a memory location, in which you can store multiple values. An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, the length is fixed. Create a class (Java1DArray) with “public static void main ….”:In single dimensional array, table/data will have a single row and column(s) and it contains values:?01234?UsernamePasswordEmailZipCity0RamaQaqaqa8@94086Sunnyvale// Read data from above table, put the data in 1D array and print thempublic class Java1DArray {public static void main(String[] args) {String username="rama";String password="qaqa";String email="qa8@";String zip="94086"; String city="Sunnyvale";//Assume above data is in excel spread sheet// Arrays// Read the data from xls and put it inside the arrayString str[]=new String[5]; // since we have 1 row and 5 columnsstr[0]="rama";str[1]="qaqa";str[2]="qa8@";str[3]="94086";str[4]="Sunnyvale";// Remember: Array holds a fixed number of values of a single type. //The length of an array is established when the array is created.// find the length of the array System.out.println(str.length); // this will print 5// Print all the elements of the String arrayfor (int x=0;x<=str.length;x++) {System.out.println(str[x]); // it will print the whole string array}}}Two Dimensional Array ****In Java, a table may be implemented as a 2D array. Each cell of the array is a variable that can hold a value and works like any variable. As with one dimensional arrays, every cell in a 2D array is of the same type. The type can be a primitive type or an object reference type.2D contains multiple rows, columns and it has data started from index 0:?0123?UsernamePasswordEmailZip0RamaQaqaQa8@940861AshokPa$$w0rdagupta@950512SnehaLuckySnehaAgar@94087Create a new class (Java2DArray) with “public static main…”://Test Case: Print all the values in above table using 2D Array:public class Java2DArray {public static void main(String[] args) {String x[][]= new String[3][4]; //3 rows and 4 columns// Selenium …. Write code here to read data from excel //first rowx[0][0]="Rama";x[0][1]="Qaqa";x[0][2]="Qa8@";x[0][3]="94086";//2nd rowx[1][0]="Ashok";x[1][1]="Pa$$w0rd";x[1][2]="agupta@";x[1][3]="95051";//3rd rowx[2][0]="Sheha";x[2][1]="Lucky";x[2][2]="SnehaAgar@";x[2][3]="94087";// In Selenium, mostly we read data from 2 dimensional array (see table example above):// **** It will basically read data from excel and put them into 2D array (but it won't read cell by cell from excel) and then the script will read the data from 2D array instead of reading from excel directly.// Print 2D array// Print rowsSystem.out.println("Rows are "+ x.length); // This will print Rows are 3// Print columnsSystem.out.println("Cols are "+ x[0].length);// This will print Cols are 4// Now print, each and every value present in 2D arrayint rows=x.length;int cols=x[0].length;for (int rowNum=0; rowNum<rows; rowNum++){System.out.println("---------------");for (int colNum=0; colNum<cols; colNum++){System.out.println(x[rowNum][colNum]); // It will print your complete 2D array}}// Only drawback is, it cannot determine in the beginning that what length of array should be there.}}Object Array/ Class In a string array, we cannot put integer. At the same time, in Integer we cannot put string. In this case, we need an array where we can put multiple types of data like string, int, char etc.. This can be done by using Object Array / Class. Object ar[] = new Object[4];ar[0]="Hello";ar[1]=1234;ar[2]="4545";ar[3]=true;ar[4]=23.21;// In Selenium, we'll use Object Arrays the most.Functions It’s an independent / small unit of execution. We can call same /reusable function from different programs to avoid the duplication of code. All the functions should be inside the class body. We cannot make a function inside the function.Create a new class “JavaFunctionsBasics” with public static void….”.Below is the main function. All code should go inside the main function.//Now prepare a class with below script://Wrong scriptpublic class JavaFunctionsBasics {public static void main(String[] args) {System.out.println("In Main");}public static void testMe() { // this is how we have to define the functionSystem.out.println("In TestMe");}}Run the above class/script, it will print only “In Main” i.e main Function.You will get an error, if you put “testMe” function inside the Main function. You need to make sure functions are created parallel within a class (per above example).If you want to print, “In TestMe” as well, then you have to call “testMe” function. Main function is the one, in which the control will come by default.//Correct scriptpublic class JavaFunctionsBasics {public static void main(String[] args) {testMe();System.out.println("In Main");}public static void testMe() {System.out.println("In TestMe");}}How to pass values thru the function?Create a new class “Java_Functions_PassInValues” with “public static void…..”.public class Java_Functions_PassInValues {public static void main(String[] args) {sumAll(3,4,5);}public static void sumAll (int a, int b, int c) {int sum=a+b+c;System.out.println(sum);}} // Run: this will print 12Practical usage of Functions in Selenium public static boolean doLogin (String username, String password) {// selenium code in java for login here...return true: // success , fail }Object Oriented Programming (OOP) ****OOP stands for Object-Oriented Programming.Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.Object-oriented programming has several advantages over procedural programming:OOP is faster and easier to executeOOP provides a clear structure for the programsOOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debugOOP makes it possible to create full reusable applications with less code and shorter development timeSelenium 3.0 / WebDriver is purely Object Oriented in nature. You have to learn OOP in order to work with Selenium and in order to learn the architecture of selenium. Object-Oriented ProgrammingObjectClassPrinciple Object Oriented Concepts in JavaAbstractionEncapsulationInheritancePolymorphismWhat is Object-Oriented Programming and Concepts?Object-Oriented Programming is a method of programming where programmers define the type of data as well the operations that the data can perform.In a nutshell, Object-Oriented Programming is a simple engineering advance to build software systems which models real-world entities using classes and objects.What is an Object?An object in terms of software programming is nothing but a real-world entity or an abstract concept which has an identity, state, and behavior.For example: Let us consider a real-life entity Car.CharacteristicsExamplesIdentityModel Number, Model Name, License Plate/ Vehicle NumberStateSpeed, Gear, Engine temperature, Fuel levelBehaviorFast, Slow, Change Of Gears, Break Down, Go Reverse, Etc.What is a Class?A class defines the structure of objects which include the state and behavior (operation).For example: Let us consider a class named Bank_Account, whose state can be represented by variables like account_number, account_type. And the behavior can be represented by methods like amount_withdraw, amount_deposit, account_closure.Principle Object Oriented Concepts in Java:AbstractionEncapsulationInheritancePolymorphism1. AbstractionThe process of highlighting the necessary and most concerned characteristics and hiding others is known as abstraction.For instance, we can consider different kinds of cars and bus which have different engine type, shape, and purpose which make them distinctive from each other. Although all of them have some general features, i.e., gearbox, engine, tire, steering, brakes, etc.So the general concept between them is that they are Vehicles. Therefore, we can display the feature common to both and exclude characteristics that are in particular concerned with car or bus.This is a figure to describe Abstraction explained with an example.Vehicle -> SUV/Sedan/AutoBus/OmniBusIn Java, abstraction can be achieved with the help of,Abstract ClassInterfaceWhat is Abstract Class in Java?A class when declared using the keyword abstract is an abstract class in java. An abstract class is extended by other classes and the methods should be implemented.For example: From the above figure, the vehicle is an abstract class which is extended by SUV, Sedan, etc.Sample code:abstract class Vehicle{ public void changeGear(){ System.out.println(“Changing the gear”); }} class SUV extends Vehicle{ public void changeGear(){ System.out.println(“Gear has been changed.”); } public static void main(String args[]){ Vehicle vehicle = new SUV(); vehicle.changeGear();}Output:Gear has been changed.What is the interface in Java?An interface, in simple words, is a draft of a class which is used to achieve abstraction. Since an interface is similar to a class, it has variables and methods (which are by default abstract).2. Encapsulation:The practice of combining data and operations into a single entity is defined as encapsulation. In Java, encapsulation can be illustrated by making the data member of class private and declare getter and setter methods to make it accessible.Encapsulation example:3. Inheritance:The process of reusing the properties of an existing class is defined as an inheritance.The class whose properties are used inherited is considered the parent or superclass. And the inheriting class is the child or subclass.Inheritance, in general, depicts the parent-child relationship in object-oriented programming, which is also called as the IS-A relationship.How do we use inheritance in JAVA?The keyword extends is used to display inheritance in Java.The syntax to depict inheritance is as follows:class Parent {........}class Child extends Parent {........}For example:class Gadget {.....}class Laptop extends Gadget {.....}class Tablet extends Gadget {.....}class Smartphone extends Gadget{....}From the above example, we can say that-Laptop IS-A Gadget, i.e., Gadget is the parent class and Laptop is the child class.Tablet IS-A Gadget, i.e., Gadget is the parent class and Tablet is the child class.Smartphone IS-A Gadget, i.e., Gadget is the parent class and Smartphone is the child class.4. Polymorphism:The word polymorphism is derived from 2 Greek words namely – ‘poly’, which means many and ‘morph’ which means forms.Therefore, the word ‘Polymorphism’ means a single operation with multiple forms.For example:Let us consider we have a class called Coffee that has a method called ingredients(). The class Coffee is inherited by 2 subclasses Latte and Cappuccino which vary in using the generic method ingredients ().So, here the action performed by ingredients() method is based on the type of object which uses it.Static & Non-Static FunctionsJava is an Object Oriented Programming(OOP) language, which means we need an object to access any method or variable inside or outside the class. However there are some special cases where we don’t need any object (or instance). In order to access static methods we don’t need any object. It can be directly called in a program or by using class name. A non-static method is always be called by using the object of class.For non-static function, create a class (Car) with “public static void main ….”://========================= non-static example ================public class Car {// non-static exampleString model;int price;int wheels;public static void main(String[] args) {// creating the object of the class (ex: browser: chrome)Car c1 = new Car(); c1.model="BMW";c1.price=62754;c1.wheels=4; // this is common in every carCar c2 = new Car();c2.model="Tesla";c2.price=96111;c2.wheels=4; // this is common in every carSystem.out.println(c1.model);System.out.println(c2.model);System.out.println(c1.wheels);System.out.println(c2.wheels);}}For static function, create a class (Car1) with “public static void main ….”:// ====================================== static example ======// static example// c1.wheels=4; // this is common in every car// let's remove wheels variable from both and put it in a common location, so that all the objects will access that from a common memory / location. In this case, change "int wheels" as static int wheels=4; that means, wheels is not part of an object now. it's now common for all objects of the car class. //========================= static example ================public class Car {// static exampleString model;int price;static int wheels=4;public static void main(String[] args) {// creating the object of the class (ex: browser: chrome)Car c1 = new Car(); c1.model="BMW";c1.price=62754;//c1.wheels=4; // this is common in every carCar c2 = new Car();c2.model="Tesla";c2.price=96111;//c2.wheels=4; // this is common in every carSystem.out.println(c1.model);System.out.println(c2.model);System.out.println(c1.wheels);System.out.println(c2.wheels);}}Note: Why main method in “public static void main(String[] args)” is static?main function is static in nature. Static things can be called with class.variable.So we can call main function directly with class.function.Note: Garbage Collection: In java, garbage collection means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management. Difference between Object and Object ReferencesObject holds memory and it is created using new keyword. Object Reference is nothing but reference to that memory. It only points to memory that object holds.For example, you must have contacts of many people in your mobile. You can use a contact to call a person. The person is actually somewhere else, but the contact helps you to call them. You can think of a Reference variable to be a contact no(phone#) and Object to be the actual person you are calling. Basically a reference variable just points to an actual object.Create a class (TestCar) with “public static void main ….”:public class TestCar {String model;public static void main(String[] args) {Car a = new Car(); //- IE - webdriver iedriver = new IEdriver();Car b = new Car(); //- FF - webdriver ffdriver = new Firefoxdriver();Car c = new Car(); //- CH - webdriver chdriver = new Chromedriver();a.model="A";b.model="B";c.model="C";System.out.println(a.model);System.out.println(b.model);System.out.println(c.model);System.out.println("------------");// Run now, you will see A, B, Ca=b;b=c;c=a;/* What modifications above will do in memory is: a=b: “a” reference will be removed and “a” will be pointed to where “b” is pointing to that is c. b=c: “b” reference will be removed and “b” will be pointed to where “c” is pointing to that is a.c=a: “c” reference will be removed and “c” will be pointed to where “a” is pointing to that is b*/ System.out.println(a.model);System.out.println(b.model);System.out.println(c.model);//Now…a.model will print b, b.model will print c and c.model will print b/*i.e the objects still remain in the memory in a particular location, but object references keep on changing. Right now, object “a” doesn’t have any object reference, and cannot be accessed so it will be destroyed by mechanism called garbage collection*/// Run now, you will see B, C, B (so A is not needed anymore, and can be destroyed by Garbage collection)}}Tip: How to increase font size in Eclipse? Go to Windows -> Preference -> General -> Appearance -> Color and Fonts -> Basics -> Text Font -> Edit -> (Change the number from ex: 10 to 14) -> OKInheritance in Java ****Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.//Parent Class: (common functions in a single program)public class CommonFunctions{public void login(){System.out.println("Successfully Logged In");}public void logout(){System.out.println("Successfully Logged Out");}}//Purchase Ticket Child Class:public class PurchaseTicket extends CommonFunctions { // PurchaseTicket extends CommonFunctions, is nothing but inheritance ... PurchaseTicket Class Inherits from CommonFunctions Class.public void testPurchase(){// purchase code is here…System.out.println("Successfully Purchased the flight ticket");}}//TestPurchaseTicket Class:public class TestPurchaseTicket {public static void main (String[] args){// creating the object of the classPurchaseTicket p = new PurchaseTicket();System.out.println("--------");p.login();p.testPurchase();p.logout();// TestPurchaseTicket can call functions from both CommonFunctions and PurchaseTicket classes since PurchaseTicket inherit from CommonFunctions class.}}//Run the TestPurchaseTicket class now…and you should see results like below:--------Successfully Logged InSuccessfully Purchased the flight ticketSuccessfully Logged OutInterface ****:Interface is something which is in-complete. Interface describes what the application supposed to do. Create an interface known as Hospital: Right click on src -> New -> Interface -> Finish. Now create 3 functions for an interface: operate(), doScan(), and doVaccination().We will not implement functions within an interface. This will tell, what hospital is offering you.//Hospital Interface:public interface Hospital {public void operate();//….. develop code here….public void doScan();//….. develop code here….public void doVaccination();//….. develop code here….}Now create, 2 new classes: FortisHospital, and GovtHospital without public static void (src->New-Class->Enter name and Finish)// Change class from “public class FortisHospital{“ to “public class FortisHospital implements Hospital{“ and Position the cursor on class name (ex: FortisHospital or GovtHospital) and click “add unimplemented methods”….it will let you add all 3 functions from Hospital Interface with @Override annotation for each function. (Need to do this for both FortisHospital, and GovtHospital classes) And you must use/implement all 3 functions. Both the classes extending the Hospital Interface. Why should we use interface rather than directly writing individual classes?The reason is that: It gives a consistency in the system. i.e., both the hospitals implementing / offering the 3 functions. Interface defines the contract. In Selenium WebDriver, we'll use Java interface to automate some of the manual test cases.// FortisHospital Classpublic class FortisHospital implements Hospital {@Overridepublic void operate() {System.out.println("Fortis Hospital Operating");}@Overridepublic void doScan() {System.out.println("Fortis Hospital Scanning");}@Overridepublic void doVaccination() {System.out.println("Fortis Hospital Vaccination");}}// GovtHospital Classpublic class GovtHospital implements Hospital{@Overridepublic void operate() {System.out.println("Govt Hospital Operating");}@Overridepublic void doScan() {System.out.println("Govt Hospital Scanning");}@Overridepublic void doVaccination() {System.out.println("Govt Hospital Vaccination");}}Create another class TestHospital with public static void main ....if you try to create an object of Hospital interface, it will give an error. ex: Hospital h = new Hospital(); Hospital class is an interface. You cannot create an object of interface.But you can create an object of implementing classes... finally your TestHospital will like below:// TestHospital Classpublic class TestHospital {public static void main(String[] args) {// Hospital h = new Hospital(); //illegal (like launching browser)FortisHospital f = new FortisHospital();f.doScan();f.doVaccination();f.operate();System.out.println("-------");GovtHospital g = new GovtHospital();g.doScan();g.doVaccination();g.operate();}}// Run now, you should see:Fortis Hospital ScanningFortis Hospital VaccinationFortis Hospital Operating-------Govt Hospital ScanningGovt Hospital VaccinationGovt Hospital OperatingAbstract Class:An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.Create a new class called StreetHospitalAssume this is a small hospital and can do only Vaccination but you cannot just use one function out of 3 from Hospital Interface. Only way you can do is… convert your regular class into abstract class like below:public abstract class StreetHospital implements Hospital{public void doVaccination(){System.out.println("StreetHospital doVaccination");}}Create another Class CommunityHospital This is little bigger hospital compared to StreetHospital. It can do Scanning and Vaccination by extending the StreetHospital.public abstract class CommunityHospital extends StreetHospital{public void doScan(){System.out.println("CommunityHospital doScan");}public void doVaccination(){System.out.println("CommunityHospital doVaccination");}}Create another Class CityHospitalThis is the biggest hospital. It extends the community hospital and it will give all 3 features including operate.public class CityHospital extends CommunityHospital{public void doScan() {System.out.println("CommunityHospital doScan");}public void doVaccination() {System.out.println("CommunityHospital doVaccination");}public void operate() {System.out.println("CityHospital Operating");}}What is the difference between Hashmap and Hashtable:Hashtable is synchronized whereas hashmap is not. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know. HashMap permits null values in it, while Hashtable not.For more info, please refer: File, Writing text into file and Reading text from files using JavaOpen eclipse and create a new class/java program CWRTestFle.java with below code:import java.io.*;public class CWRTestFle {public static void main (String[] args) throws IOException {// creating text file (below line of code will create new text file automatically)File f = new File ("C:\\Selenium\\0616\\JavaIntro\\textfile.txt"); f.createNewFile();// writing text into above text fileFileWriter w = new FileWriter ("C:\\Selenium\\0616\\JavaIntro\\textfile.txt");BufferedWriter out = new BufferedWriter(w);out.write("writing data into text file");out.newLine(); // like press enter key to go to next lineout.write("This is a new line");out.flush();// Reading data from above text fileFileReader r = new FileReader ("C:\\Selenium\\0616\\JavaIntro\\textfile.txt");BufferedReader bfr = new BufferedReader(r);String x ="";while ((x=bfr.readLine()) !=null){System.out.println(x);}}}Right click on the java program -> 1JavaApplication. You should see textfile.txt created with data under C:\Selenium\0616\JavaIntro and you should see the data in Eclipse (Console tab in the bottom).NOTE: In Selenium WebDriver Data Driven / Parameterize Test, we need to write a code to read data from a file (excel, csv, xml etc) to test some test cases like login/ logout with different user accounts.To learn more about Java, please refer below website: ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download