Abstract class in Java With Example programs



Def : Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember

  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have constructors and static methods also.
  • It can have final methods which will force the subclass not to change the body of the method.




Abstract class

If a class contain any abstract method then the class is declared as abstract class. 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.
Syntax :
abstract class class_name { }

Abstract method

Method that are declared without any body within an abstract class are called 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.
Syntax :
abstract return_type function_name (); //No definition

Example of Abstract class

abstract class A
{
 abstract void callme();
}
class B extends A
{
 void callme()
 {
  System.out.println("this is callme.");
 }
 public static void main(String[] args)
 {
  B b = new B();
  b.callme();
 }
}

Abstract class with concrete(normal) method.

Abstract classes can also have normal methods with definitions, along with abstract methods.
abstract class A
{
 abstract void callme();
 public void normal()
 {
  System.out.println("this is concrete method");
 }
}
class B extends A
{
 void callme()
 {
  System.out.println("this is callme.");
 }
 public static void main(String[] args)
 {
  B b = new B();
  b.callme();
  b.normal();
 }
}

Abstraction using abstract class

Abstraction is an important feature of OOPS. It means hiding complexity. Abstract class is used to provide abstraction. Although it does not provide 100% abstraction because it can also have concrete method. Lets see how abstract class is used to provide abstraction.
abstract class Vehicle
{
   public abstract void engine();
}
public class Car extends Vehicle {

    public void engine()
    {
        System.out.println("Car engine");
        //car engine implementation
    }

    public static void main(String[] args)
    {
        Vehicle v = new Car();
        v.engine();
    }
}









Comments