Selenium – Basics of Java Part 3

Working with Classes, Objects and Methods

Declaring Classes – You have seen classes defined in the following way:

Class MyClass {

// field, constructor, and

// method declarations

}

This is a class declaration. The class body contains all the code that provide for the lifecycle of the objects created from the class.

In general, class declarations can include these components, in order:

  1. Modifiers such as public, private etc.
  2. The class name, with initial letter capitalized by convention
  3.   The name of the class’s parent if any, preceded by the keyword extends. A class can only extends one parent.
  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implements more than one interface.
  5. The class body, surrounded by braces, {}

Declaring Member Variables – There are several kinds of variables:

  • Member variables in a class – these are called fields.
  • Variables in method or block of code – these are called local variables
  • Variables in method declarations – these are called parameters

Defining Methods or Functions

Here is an example of a typical method declaration:

public double calculateAns(double WingSpan, int numberOfEngine, double length) {

//do the calculation here

}

More generally, method declaration have six components, in order:

  1. Modifiers – such as public, private etc.
  2. The return type – the data type of the value returned by the method, or void if the method does not return a value.
  3. The method name – the rules for field names apply to method names as well, but the convention is a little different.
  4. The Parameter list in parenthesis –  a comma-delimited list of  input parameters, preceded by their data types, enclosed by parentheses (). If there are no parameters you must use empty parentheses.
  5. An exception list – a comma-delimited list of exception
  6.  The method body, enclosed between braces – the method’s code, including the declaration of local variables, goes here.

Overloading Methods

The Java programming language supports overloading methods and java can distinguish between methods with different method signatures. This means method within a class can have the same name if they have different parameter lists.

public class DataArtist {

public void draw(String s) {

//write code here

}

public void draw(int i) {

//write code here

}

public void draw(double f) {

//write code here

}

public void draw(int i, double f) {

//write code here

}

}

Providing Constructors for Your Classes

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations – except that they use the name of the class and have no return type.

 

public class DataArtist {

public DataArtist() {

//write code here

}

public void draw(int i) {

//write code here

}

}

Returning a value from a method – A method returns to the code that invoked it when it

  • Completes all the statements in the method
  • reaches a return statement
  • throws an exception

whichever occurs first.

Using the this Keyword

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Using this with a Field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:

public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Each argument to the constructor shadows one of the object’s fields — inside the constructor x is a local copy of the constructor’s first argument. To refer to the Point field x, the constructor must use this.x.

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here’s another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle {
private int x, y;
private int width, height;

public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}

}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle’s member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1×1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.

Exception Handling

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s instructions.

Exception Handling is a mechanism to handle run-time errors such as ClassNotFound, IO, SQL, Remote etc.

There are 5 keywords used in java exception handling.

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

To catch an exception we first put the code which we suspect to throw an error into a try block like

WebElement txtbox_username = driver.findElement(By.id(“username”));

try {

if (txtbox_username.isEnabled()) {

txtbox_username.sendKeys(“automation”);

}

}

catch(NoSuchElementException e) {

System.out.println(e.toString());

}

Followed by a catch block of code where we tell the system what should be done when the exception occurs. Generally this is where we display the message of the exception object so that we know which exception has occurred and why.

Multiple catch blocks – A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

try {

file = new FileInputStream(filename);

x = (byte) file.read();

}catch(IOException I) {

i.printStackTrace();

return -1;

}catch(FileNotFoundException f) {

f.printStackTrace();

return -1;

}

The throws/throw Keywords

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.  You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Let us try to understand the difference in throws and throw keywords.

The following method declares that it throws a ArithmeticException. Since the exception is  not handled from within the code, we are using throw keyword to throw ArithmeticException.

The syntax of java throw keyword is given below.
throw exception;

public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException(“not valid”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args[]){
validate(13);
System.out.println(“rest of the code…”);
}
}

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}

class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println(“normal flow…”);
}
}

Finally block

Java finally block is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println(“finally block is always executed”);}
System.out.println(“rest of the code…”);
}
}

Leave a Reply Cancel reply