Abstract Method and Class in Java
In this class, We discuss Abstract Method and Class in Java.
The reader should have prior knowledge of object-oriented Programming concepts. Click Here.
First, we understand what abstract method and class is. Then we discuss the use of the abstract class.
Example:
Abstract class A
{
void m1()
{
System.out.println(“this is m1 method in class A”);
}
}
class test
{
public static void main(String args[])
{
A ob = new A(); // can not instantiate
ob.m1();
}
}
Writting abstract keywords before class is called an abstract class.
An abstract class can not be instantiated. I.e., we can not create an object for abstract classes.
Abstract Method:
Abstract class A
{
void m1()
{
System.out.println(“this is m1 method in class A”);
}
abstract void m2();
}
Class B extends A
{
void m2()
{
System.out.println(“m2 method written in class B”);
}
}
class test
{
public static void main(String args[])
{
B ob = new B();
ob.m1();
}
}
Abstract methods do not have a body.
In the above example, m2 is an abstract method declared in class A.
Suppose atleast one method is abstract. Then the class should be abstract.
Abstract methods do not have a body. So we are not supposed to create objects. Hence class should be abstract.
Suppose any class inherits the abstract class. Then the class should implement all the abstract methods.
In the above example, class B should implement the method m2.
Use of abstract class and method.
Take a university application example.
If we take any university, 80% of the logic is similar.
20% of the logic is different for each University.
Example:
Finding the tax of employees is the same for any university because tax is related to the government.
Finding CGPA is different for each University.
We take an abstract class at University. Tax logic is written, and CGPA is made abstract method.
abstract class university
{
void tax()
{
}
abstract void CGPA();
}
Class LPU extends University.
{
void CGPA()
{
}
}
Class KLU Extends University
{
void CGPA()
{
}
}
LPU and KL University inherit university classes because 80% of the code is identical.
The remaining logic is written for its purpose.