Abstract class
There is a situation in which you want to define a super class that
declares the structure of a given abstraction without providing a
complete implementation of every method.
That is sometimes you want to create a super class or parent class that
only defines a generalized method and that method you want to share
by all of its sub-classes or child classes, leaving it to be each sub class
to implement method.
Abstract class determines the nature of the methods that the sub-
classes must implement.
Abstract class means a class which is declared with the “abstract”
keyword and abstract class may or may not include abstract method.
Abstract methods means a method which are only declared but not
defined (means abstract method does not have body).
Abstract class needs to be extended and its method
implemented. Means the abstract methods which are there in
super class must be override in sub-class otherwise it will give
you error message.
We can’t create an instance/object of an abstract class because it is an
incomplete class.
Features of an Abstract Class:
o An abstract class must be declared with an abstract keyword.
o It can have abstract methods and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change
the body of the method.
1
Eg:
abstract Shape
public abstract void draw();
Triangle Rectangle Square
In this example, Shape is the abstract class, and its implementation is provided by the Triangle
Rectangle and Square classes.
Syntax to create abstract class:
<abstract> <class> <calss_name>
{
//body
}
Syntax to create abstract method:
<access-modifier> <abstract> <retruen-type> <method_name>()
{
2
abstract class Shape{
abstract void draw();
//In real scenario, implementation is provided by others i.e. unknown by end user
class Triangle extends Shape{
void draw(){[Link]("drawing triangle");}
class Rectangle extends Shape{
void draw(){[Link]("drawing rectangle");}
class Square extends Shape{
void draw(){[Link]("drawing square");}
//In real scenario, method is called by programmer or user
class Area{
public static void main(String args[]){
Triangle t=new Triangle();
[Link]();
Rectangle r=new Rectangle();
[Link]();
3
Q: We have to calculate the area of a rectangle, a square and a circle. Create
an abstract class 'Shape' with three abstract methods namely
'RectangleArea' 'SquareArea' and 'CircleArea'. Now create another class
'Area' inheriting the class “Shape”. Class 'Area' containing all the three
methods 'RectangleArea', 'SquareArea' and 'CircleArea' for printing the area
of rectangle, square and circle respectively. Create an object of class 'Area'
and call all the three methods.
import [Link].*;
public abstract class Shape {
public abstract void rectangleArea();
public abstract void squareArea() throws IOException;
public abstract void circleArea()throws IOException;;
}
import [Link].*;
public class Area extends Shape {
int l,b,s,r;
double a;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
public void rectangleArea()
{
try{
[Link]("Enter the length:");
l=[Link]([Link]());
[Link]("Enter the width:");
b=[Link]([Link]());
a=l*b;
[Link]("Area of Rectangle:"+a);
}catch(Exception ex){[Link]();}
}
public void squareArea() throws IOException
{
[Link]("Enter the side:");
s=[Link]([Link]());
a=s*s;
[Link]("Area of SquareArea:"+a);
}
4
public void circleArea() throws IOException
{
[Link]("Enter the radius:");
r=[Link]([Link]());
a=[Link]*[Link](r,2);
[Link]("Area of CircleArea:"+a);
}
public static void main(String args[]) throws IOException
{
Area a=new Area();
[Link]();
[Link]();
[Link]();
}
}
Q: We have to calculate the area of a rectangle, a square and a circle. Create
an abstract class 'Shape' with three abstract methods namely
'RectangleArea' taking two parameters, 'SquareArea' and 'CircleArea' taking
one parameter each. The parameters of 'RectangleArea' are its length and
width, that of 'SquareArea' is its side and that of 'CircleArea' is its radius.
Now create another class 'Area' inheriting the class “Shape”. Class 'Area'
containing all the three methods 'RectangleArea', 'SquareArea' and
'CircleArea' for printing the area of rectangle, square and circle respectively.
Create an object of class 'Area' and call all the three methods.
public abstract class Shape {
public abstract void rectangleArea(int l,int b);
public abstract void squareArea(int side);
public abstract void circleArea(int r);
}
import [Link].*;
public class Area extends Shape {
double a;
public void rectangleArea(int l,int b)
{
a=l*b;
[Link]("Area of Rectangle:"+a);
}
public void squareArea(int side)
5
{
a=side*side;
[Link]("Area of SquareArea:"+a);
}
public void circleArea(int r)
{
a=[Link]*[Link](r,2);
[Link]("Area of CircleArea:"+a);
}
public static void main(String args[])
{
int l,b,s,r;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
Area a=new Area();
try{
[Link]("Enter the length:");
l=[Link]([Link]());
[Link]("Enter the width:");
b=[Link]([Link]());
[Link](l,b);
[Link]("Enter the side:");
s=[Link]([Link]());
[Link](s);
[Link]("Enter the radius:");
r=[Link]([Link]());
[Link](r);
}catch(Exception ex){[Link]();}
}
}
6
Q: Create an abstract class 'Animal' with abstract method display(). Now
create a class 'Dog' with a method 'display' which prints "Dogs bark" and a
class 'Tiger' with a method display() which prints "Tiger roar", both inheriting
the class 'Animal'. Now create an object for each of the subclasses and call
their respective methods.
abstract class Animal
{
public abstract void display();
};
class Dog extends Animal
{
public void display()
{
[Link]("Dogs bark.");
}
};
class Tiger extends Animal
{
public void display()
{
[Link]("Tiger roar.");
}
}
public class TPoly
{
public static void main(String args[])
{
Animal ani;
ani=new Dog();
[Link]();
ani=new Tiger();
[Link]();
7
Q: Create an abstract class 'Bank' with an abstract method getRateOfInterest
7, 7.5 and 8 are interest rate in banks SBI, PNB and UCO Bank respectively.
SBI, PNB and UCO are subclasses of class 'Bank', each having a method
named getRateOfInterest. Create a reference variable of class Bank and call
all the three methods of SBI, PNB and UCO class.
Eg:
abstract class Bank{
abstract int getRateOfInterest();
class SBI extends Bank{
int getRateOfInterest(){return 7;}
class PNB extends Bank{
int getRateOfInterest(){return 7.5;}
class UCO extends Bank{
int getRateOfInterest(){return 8;}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
[Link]("SBI Rate of Interest is: "+[Link]()+" %");
b=new PNB();
[Link]("PNB Rate of Interest is: "+[Link]()+" %");
8
b=new UCO();
[Link]("UCO Rate of Interest is: "+[Link]()+" %");
}}
Abstract class having constructor, data member and methods
An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor.
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike(){[Link]("bike is created");}
abstract void run();
void changeGear(){[Link]("gear changed");}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){[Link]("running safely..");}
//Creating a Test class which calls abstract and non-abstract methods
class Test{
public static void main(String args[]){
Bike obj = new Honda();
9
[Link]();
[Link]();
Output:
bike is created
running safely..
gear changed
Question: Define an abstract class Staff with members’ names and
addresses and abstract method i.e. accept and display. Define two sub-
classes of this class – “FullTimeStaff” (department, salary) and
“PartTimeStaff” (number-of-hours, rate-per hour). Create “N” objects which
could be of either FullTimeStaff or PartTimeStaff class by asking the user’s
choice. Display details of all “FullTimeStaff” or all “PartTimeStaff”.
import [Link];
import [Link];
import [Link];
abstract class Staff{
String name,address;
public abstract void accept();
public abstract void display();
}
class FullTimeStaff extends Staff{
String department;
double salary;
public void accept() throws IOException{
[Link]("Enter the name, address, department and salary: ");
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
name=[Link]();
address=[Link]();
10
department=[Link]();
salary=[Link]([Link]());
}
public void display(){
[Link]("Name: "+name);
[Link]("Address: "+address);
[Link]("Department: "+department);
[Link]("Salary: "+salary);
[Link]("----------------------");
}
}
class PartTimeStaff extends Staff{
int hours, rate;
public void accept() throws IOException{
[Link]("Enter the name, address, No of working hours and rate
per hour: ");
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
name=[Link]();
address=[Link]();
hours=[Link]([Link]());
rate=[Link]([Link]());
}
public void display(){
[Link]("Name: "+name);
[Link]("Address: "+address);
[Link]("No of Working Hours: "+hours);
[Link]("Rate per hour: "+rate);
[Link]("----------------------");
}
11
}
public class Menu {
public static void main(String [] args) throws IOException{
int i;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
[Link]("[Link] Time Staff");
[Link]("[Link] Time Satff");
[Link]("Select Any One: ");
int ch=[Link]([Link]());
switch(ch){
case 1:
[Link]("Enter the number of Full Time Staff: ");
int n=[Link]([Link]());
FullTimeStaff [] l=new FullTimeStaff[n];
for(i=0;i<n;i++){
l[i]=new FullTimeStaff();
l[i].accept();
}
for(i=0;i<n;i++){
l[i].display();
}
break;
case 2:
[Link]("Enter the number of Part Time Staff: ");
int m=[Link]([Link]());
PartTimeStaff [] h=new PartTimeStaff[m];
12
for(i=0;i<m;i++){
h[i]=new PartTimeStaff();
h[i].accept();
}
for(i=0;i<m;i++){
h[i].display();
}
break;
}
}
}
Q: Create an abstract class CalculatorOperation with the
following abstract method i.e add(), sub(), multi() and
div().
Create a menu driven program in Calculator class that
such as 1 for Addition, 2 for Subtract, 3 for Multiplication,
4 for Division and 5 for Exit. A Class Calculator that
implements the abstract class CalculatorOperation .
Q. Write a JAVA program which has
i. An Abstract class for Stack Operations
ii. A Class that implements the abstract Stack class and
creates a fixed length Stack.
13
Define an abstract class Staff with abstract method i.e.
accept and display. Define two sub-classes of this class i.e.
Employee and Manger. Employee class having members – id, name,
department, salary and Manager class with private member bonus and total-
salary. Create “N” number of objects of the Manager class and display the
details of the manager having the maximum total salary (i.e. salary+bonus).
import [Link].*;
abstract class Staff
{
public abstract void accept()throws IOException;
public abstract void display();
}
class Emp extends Staff{
int id;
double salary;
private String name,dept;
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
@Override
public void accept() throws IOException{
[Link]("Enter id of employee: ");
id=[Link]([Link]());
[Link]("Enter name of employee: ");
name=[Link]();
[Link]("Enter salary of employee: ");
salary=[Link]([Link]());
[Link]("Enter department of employee: ");
dept=[Link]();
}
14
@Override
public void display(){
[Link]("Emp Id: "+id);
[Link]("Name: "+name);
[Link]("Salary: "+salary);
[Link]("Department: "+dept);
}
}
public class Manager extends Emp{
private double bonus;
double tsalary;
@Override
public void accept() throws IOException{
[Link]();
[Link]("Enter Bonus of employee: ");
bonus=[Link]([Link]());
tsalary=salary+bonus;
}
@Override
public void display(){
[Link]();
[Link]("Bonus: "+bonus);
[Link]("Total Salary: "+tsalary);
}
public static void main(String[] args) throws IOException{
Manager[] m=new Manager[10];
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the number of employees: ");
int n=[Link]([Link]());
for(int i=0;i<n;i++){
m[i]=new Manager();
15
m[i].accept();
}
for(int i=0;i<n;i++){
m[i].display();
[Link]("---------------------------------");
}
double maxx=m[0].tsalary;
for(int i=0;i<n;i++){
if(m[i].salary>maxx)
{
maxx=m[i].tsalary;
}
}
[Link]("The Employee having the maximum Total
salary is :");
for(int i=0;i<n;i++)
{
if(m[i].tsalary==maxx)
m[i].display();
}
}
}
16
Features of an Abstract Class:
1. Cannot be instantiated:
You cannot create an object directly from an abstract class.
2. Can contain abstract methods:
These are methods declared with the abstract keyword and have no
implementation (no method body). Subclasses must provide an
implementation for these abstract methods unless the subclass itself
is also declared as abstract.
3. Can contain concrete (non-abstract) methods:
Abstract classes can also have regular methods with full
implementations, providing common functionality for their subclasses.
4. Can have constructors:
Abstract classes can have constructors, which are typically called by
the constructors of their subclasses using super().
5. Can have static and final methods:
Similar to concrete classes, abstract classes can include static
methods and methods declared as final (preventing overriding by
subclasses).
6. Inheritance:
Abstract classes are meant to be extended by other classes
(subclasses) using the extends keyword.
Purpose of an Abstract Class:
1. Achieve abstraction:
Abstract classes enable abstraction by defining a common interface
and behavior for a group of related classes while hiding
implementation details. They specify "what" needs to be done without
dictating "how."
2. Provide a common template:
They act as a base class, offering a shared structure and some
implemented functionality to a hierarchy of related classes.
3. Enforce method implementation:
By including abstract methods, abstract classes enforce a contract on
their subclasses, ensuring that specific methods are implemented by
each subclass according to its unique requirements.
4. Promote code reusability:
Concrete methods within an abstract class provide reusable code that
can be inherited and utilized by all subclasses.
5. Support polymorphism:
17
Abstract classes, along with their subclasses, facilitate polymorphism,
allowing a single reference variable of the abstract class type to refer
to objects of its various concrete subclasses.
18