Selenium and Java

Selenium and Java

Wednesday, 4 December 2019

JAVA- Methods


Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()

JAVA Basics

JAVA Basics...
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding of Java. This reference will take you through simple and practical approaches while learning Java Programming language.

  • Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
  • Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
  • Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP (object Oriented Program) Java, it would be easy to master.
  • Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
  • Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.
  • Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.
  • Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.

Wednesday, 5 August 2015

Java - Set collection interfaces

Set collection interface:

A Set is a Collection that cannot contain duplicate elements. The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet

HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not
guarantee that the order will remain constant over time. This class permits the null element.

   HashSet<String> hs =new HashSet<String>();
   hs.add("Name 1");
   hs.add("Name 2");
   hs.add("Name 3");

      int sizehashset = hs.size();
      System.out.println(sizehashset);
      Iterator<String> itr=hs.iterator();

    while(itr.hasNext()){
         System.out.println(itr.next()); }
   hs.contains(Object) ;
   hs.clear();

TreeSet : TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order. The TreeSet class implements NavigableSet interface that extends the SortedSet interface. Access and retrieval times are quite fast.

LinkedHashSet :  LinkedHashSet is between HashSet and TreeSet. It is implemented as a hash table with a linked list running through it, so it provides the order of insertion.
LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set.

Java - Collections

Collections

A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).

The core collection interfaces encapsulate different types of collections, which are shown in the figure below. These interfaces allow collections to be manipulated independently of the details of their representation. Core collection interfaces are the foundation of the Java Collections Framework. As you can see in the following figure, the core collection interfaces form a hierarchy.




A Set is a special kind of Collection, a SortedSet is a special kind of Set, and so forth. Note also that the hierarchy consists of two distinct trees — a Map is not a true Collection.

The following list describes the core collection interfaces:


Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List. Also see The Collection Interface section.

Set — a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine. See also The Set Interface section.
List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). If you've used Vector, you're familiar with the general flavor of List. Also see The List Interface section.
Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.

Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements' natural ordering. Whatever the ordering used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties. Also see The Queue Interface section.
Deque — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Deque provides additional insertion, extraction, and inspection operations.

Deques can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-out). In a deque all new elements can be inserted, retrieved and removed at both ends. Also see The Deque Interface section.
Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. If you've used Hashtable, you're already familiar with the basics of Map. Also see The Map Interface section.

The last two core collection interfaces are merely sorted versions of Set and Map:
SortedSet — a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls. Also see The SortedSet Interface section.
SortedMap — a Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories. Also see The SortedMap Interface section.

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No.MethodDescription
1public boolean add(Object element)is used to insert an element in this collection.
2public boolean addAll(collection c)is used to insert the specified collection elements in the invoking collection.
3public boolean remove(Object element)is used to delete an element from this collection.
4public boolean removeAll(Collection c)is used to delete all the elements of specified collection from the invoking collection.
5public boolean retainAll(Collection c)is used to delete all the elements of invoking collection except the specified collection.
6public int size()return the total number of elements in the collection.
7public void clear()removes the total no of element from the collection.
8public boolean contains(object element)is used to search an element.
9public boolean containsAll(Collection c)is used to search the specified collection in this collection.
10public Iterator iterator()returns an iterator.
11public Object[] toArray()converts collection into array.
12public boolean isEmpty()checks if collection is empty.
13public boolean equals(Object element)matches two collection.
14public int hashCode()returns the hashcode number for collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:
  1. public boolean hasNext(): it returns true if iterator has more elements.
  2. public object next() : it returns the element and moves the cursor pointer to the next element.
  3. public void remove(): it removes the last elements returned by the iterator. It is rarely used.

Tuesday, 4 August 2015

Selenium - Handling multiple iFrames in Selenium Webdriver

An inline frame is used to embed another document within the current HTML document. It means iframe is actually a webpage within the webpage which have its own DOM for every iframe on the page.

Once the frame is selected or navigated , all subsequent calls on the WebDriver interface are made to that frame. i.e the driver focus will be now on the frame. What ever operations we try to perform on pages will not work and throws element not found as we navigated / switched to Frame.
We can select an iFrame using the below metthods:

1. by index: frame(index):  We can use index of the frame to get focus on the frame. index start with 0. 

   driver.switchTo().frame(0) ;// focus on 0th frame

   Parameters: Index - (zero-based) index
   Returns: driver focused on the given frame (current frame)
   Throws: NoSuchFrameException - If the frame is not found.

2. by name : frame(Name of Frame) : We can use name of the frame instead of index to get frame.

      driver.switchTo().frame(frameName) ;// focus on frame with name frameName

    Parameters: name Or Id - the name of the frame or the id of the frame element.
    Returns: driver focused on the given frame (current frame)
   Throws: NoSuchFrameException - If the frame is not found

3. by Id: frame(Id of the frame): We can also use Id of the frame as below

  driver.switchTo().frame(frameID) ;// focus on frame with ID as frameId

    Parameters: name Or Id - the name of the frame or the id of the frame element.
    Returns: driver focused on the given frame (current frame)
   Throws: NoSuchFrameException - If the frame is not found

4. by locating frame like other element: frame(WebElement frameElement)

  First locate frame with any web element locator and use webelement.

 Webelement el = driver.findelement(by.xpath(".//iframe[@title='ABC']"));
 driver.switchTo().frame(el);

    Parameters: frameElement - The frame element to switch to.
    Returns: driver focused on the given frame (current frame).
    Throws: NoSuchFrameException - If the given element is neither an iframe nor a frame element. And StaleElementReferenceException - If the WebElement has gone stale.

5. switching outside frame : defaultContent()

  driver.switchTo().defaultContent();

6. switch to multiple frame : 

driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);

Tuesday, 28 July 2015

Java -this() keyword

this() keyword :

this is a keyword in Java. Which can be used inside method or constructor of class. It(this) works as a reference to current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor.


Java - Constructors

Constructors :


  • Java constructors are the methods which are used to initialize objects. 
  • Constructor method has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly. 
  • Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially. 
  • It is optional to write constructor method in a class but due to their utility they are used. 
  • Constructor method doesn't specify a return type, they return instance of class itself.
  • Default constructor provides the default values to the object like 0, null etc. depending on the type.


Java constructor overloading

Like other methods in java constructor can be overloaded i.e. we can create as many constructors in our class as desired. Number of constructors depends on the information about attributes of an object we have while creating objects


Rules for creating java constructor

There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type
Java ConstructorJava Method
Constructor is used to initialize the state of an object.Method is used to expose behaviour of an object.
Constructor must not have return type.Method must have return type.
Constructor is invoked implicitly.Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor.Method is not provided by compiler in any case.
Constructor name must be same as the class name.Method name may or may not be same as class name.

Monday, 27 July 2015

Java- Abstract class and method

Abstraction: 
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Abstraction is a process of hiding the implementation details and showing only functionality to the user.
There are two ways to achieve abstraction in java
  1. Abstract class (0 to 100%)
  2. Interface (100%)
Abstract Class : A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).  An abstract class is never instantiated. It is used to provide abstraction. Although it does not provide 100% abstraction because it can also have concrete method.

abstract class class_name { }

Abstract Method: Method that are declared without any body within an abstract class is known as abstract method. The method body will be defined by its subclass. Abstract method can never be final and static. Any class that extends an abstract class must implement all the abstract methods declared by the super class.

abstract return_type function_name ();    

Java - Garbage Collection

Java Garbage Collection:

Advantage of Garbage Collection
  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

In java, garbage 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.
In java it is performed automatically. So, java provides better memory management.

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:

protected void finalize(){}

Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

Java - Interface

Interface :

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
The interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction.  There can be only abstract methods in the java interface.

The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data members.

An interface is different from a class in several ways, including:
  • You cannot instantiate an interface.
  • An interface does not contain any constructors.
  • All of the methods in an interface are abstract.
  • An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
  • An interface is not extended by a class; it is implemented by a class.
  • An interface can extend multiple interfaces.
Class and Interface:

  • Class can Extend another Class
  • Class can Implement Interface
  • Interface can Extend another Interface

Multiple inheritance in Java by interface:

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

For example, if the Cricket interface extended both Sports and Event, it would be declared as:
public interface Hockey extends Sports, Event

  • Class1 implements Interface 1 and Interface 2  or
  • Interface1 extends Interface2 and Interface3

Marker or tagged interface:

An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.

Saturday, 25 July 2015

Java- super Keyword

super keyword in java

The super keyword in java is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.

Usage of java super Keyword

  1. super is used to refer immediate parent class instance variable.
  2. super() is used to invoke immediate parent class constructor.
  3. super is used to invoke immediate parent class method.
Without super keyword...
class Vehicle{
  int speed=50;
}
class Bike3 extends Vehicle{
    int speed=100;
    void display(){
    System.out.println(speed);//will print speed of Bike
  }
  public static void main(String args[]){
    Bike3 b=new Bike3();
    b.display();
  }
}
Output : 100

With super keyword...

//example of super keyword
class Vehicle{
  int speed=50;
}
class Bike4 extends Vehicle{
  int speed=100;
   
  void display(){
   System.out.println(super.speed);//will print speed of Vehicle now
  }
  public static void main(String args[]){
   Bike4 b=new Bike4();
   b.display();
  
  }
}
Output : 50

 

Friday, 24 July 2015

Java - Inheritance

Inheritance : 

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.

A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.





What We Can Do in a Subclass

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:
  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can declare new methods in the subclass that are not in the superclass.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.

Thursday, 23 July 2015

Java- Exceptions

Exception in Java:  An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread's method invocation stack.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of exceptions


  • Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
  • Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
  • Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.



Checked vs Unchecked Exceptions in Java


In Java, there two types of exceptions:
1) Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
For example, consider the following Java program that opens file at locatiobn “C:\test\a.txt” and prints first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException


import java.io.*;
class Main {
  public static void main(String[] args) {
     FileReader file = new FileReader("C:\\test\\a.txt");
     BufferedReader fileInput = new BufferedReader(file);
     // Print first 3 lines of file "C:\test\a.txt"
     for (int counter = 0; counter < 3; counter++)
       System.out.println(fileInput.readLine());
    fileInput.close();
  }
}

To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.

import java.io.*;
  class Main {
     public static void main(String[] args) throws IOException {
         FileReader file = new FileReader("C:\\test\\a.txt");
         BufferedReader fileInput = new BufferedReader(file);
         // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++)
          System.out.println(fileInput.readLine());
        fileInput.close();
      }
   }

2) Unchecked (Runtime)  : are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. 
Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile, because ArithmeticException is an unchecked exception.
class Main {
    public static void main(String args[]) {
      int x = 0;
      int y = 10;
     int z = y/x;
    }
}


Exception handling: Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Wednesday, 22 July 2015

Java- Class and its Variables

Class:

A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.
A class consist of Local variable, instance variables and class variables.

Local variable:
Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.

Instance variable:
Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.

Class variables:
These are variables declared with in a class, outside any method, with the static keyword.
Instance VariableClass Variable
Instance variables are declared in a class, but outside a method, constructor or any block Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Static variables are created when the program starts and destroyed when the program stops.
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName. Static variables can be accessed by calling with the class name ClassName.VariableName.
Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.There would only be one copy of each class variable per class, regardless of how many objects are created from it.

Java- Objects

Objects in Java:

Let us now look deep into what are objects. If we consider the real-world we can find many objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging, running
If you compare the software object with a real world object, they have very similar characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields and behavior is shown via methods.An object is an instance of a class.
So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

Friday, 26 June 2015

Java- Throw, Throws, Throwable

Java- Throw, Throws, Throwable

Throw:

throw is a keyword in java which is used to throw an exception manually. Using throw keyword, you can throw an exception from any method or block. But, that exception must be of type java.lang.Throwable class or it’s sub classes. Below example shows how to throw an exception using throw keyword.

class ThrowAndThrowsExample
{
 void method() throws Exception
 {
  Exception e = new Exception();

  throw e;            //throwing an exception using 'throw'
 }
}

Thursday, 25 June 2015

Java- Final , Finally and Finalize

Java- Final , Finally and Finalize

Final:

Final is a keyword. The variable decleared as final should be initialized only once and cannot be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be overridden.Final is a keyword.

final can be used to mark a variable "unchangeable"

private final String name = "foo";  //the reference name can never change

final can also make a method not "overrideable"

public final String toString() {  return "NULL"; }

final can also make a class not "inheritable". i.e. the class can not be subclassed.

public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed

Finally:

Finally is a block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. Finally is a block.


lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}

Finalize:

Finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in finalize() method before getting garbage collected. Finalize is a method.

Wednesday, 24 June 2015

Selenium - Excel creation using APACHE POI in selenium Webdriver framework

Code to create Excel sheet at run time using APACHE POI..


String filepath = "D:\\Mohit1.xls";

FileOutputStream fileout = new FileOutputStream(filepath);

Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet();

Row row;
Cell cell;
for (int i=0 ; i< 4 ; i++){

row = sheet.createRow(i);
for (int j =0 ; j<3 ;j++){

cell = row.createCell(j);
cell.setCellValue("data"+ i + j);
}
}

workbook.write(fileout);

Selenium - Selenium IDE

Selenium IDE is a Firefox plug in , we can record actions on webpage like type, select , click  and we can play back same recorded script again to verify the action.

Java - Overriding method


Overriding Method :


Method in a subclass with the same signature (name,number and the type of its parameters) and return type as method in the super class overrides the super class's method.

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.

In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.


Super keyword in Overriding


super keyword is used for calling the parent class method/constructor. super.methodname() calling the specified method of base class while super() calls the constructor of base class. Let’s see the use of super in Overriding



Static Methods


If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:
  1. The version of the overridden instance method that gets invoked is the one in the subclass.
  2. The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

Advantage of method overriding :

The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class(base class).


Rules of method overriding in Java:

  1. Argument list: The argument list of overriding method must be same as that of the method in parent class. The data types of the arguments and their sequence should be maintained as it is in the overriding method.
  2. Access Modifier: The Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of base class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier as all of the three are more restrictive than public.
  3. Private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.
  4. Overriding method (method of child class) can throw any unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.
  5. If a class is extending an abstract class or implementing an interface then it has to override all the abstract methods unless the class itself is a abstract class
Example of Overriding in Java:


public class OverrideBaseClass {

public int add (int a,int b){
int c= a+b;
return c;
}
}
public class OverridingChildClass extends OverrideBaseClass {

public int add (int a,int b){
System.out.println("Addition is " +super.add(5,6));
int c= a+b+5;
return c;
}
public static void main(String[] args) {

OverrideBaseClass overr = new OverridingChildClass();
System.out.println("Addition is " + overr.add(5,6));
}
}



Output: 
Addition is 11
Addition is 16