Java Abstract Class with Examples
Overview
In this tutorial, we will discuss the Java Abstract class concept. Any class that contains one or more abstract methods is called an abstract class. We can use the abstract keyword to declare and create the abstract class. We cannot create objects for the abstract class. It’s up to the subclass or derived class to provide meaningful implementations of the abstract methods.
Examples
Let’s create an abstract class called Shape.
Shape class
package oops; //Abstract Shape super class public abstract class Shape { private String shapeName; public Shape(String name) { this.shapeName = name; } public String getName() { return shapeName; } public void setName(String name) { this.shapeName = name; } public abstract double calcArea(); }
As shown in the class, calcArea() is an abstract method. This method is not defined in the Shape class. Now let’s define the Rectangle class (a subclass of the Shape class) and give implementation to the abstract method.
Rectangle class
The Rectangle class is the concrete class with actual implementations for the abstract method. We can instantiate and create objects for the Rectangle class.
package oops; //Rectangle is subclass of Shape public class Rectangle extends Shape { private double width; private double length; public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public Rectangle(String name,double wid,double len ) { super(name); this.width=wid; this.length=len; } @Override public double calcArea() { return width*length; } }
In the Rectangle class we have overridden the abstract method and provided implementation to the calcArea() method as per the rectangle area calculation.
Selenium API Example
By is an abstract class in Selenium API. This class outlines locating mechanisms for finding web elements on the page. The abstract method in the class is findElements()
public abstract List<WebElement> findElements(SearchContext context);
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :