What is Abstract Class and Abstract Method in Java with Examples


In this article, we will learn what is an abstract class, what are rules to define an abstract class, abstract class usage, real-world examples and how to use in real time projects.

Java Abstract Class Basics

1. Abstract Class

An abstract class is a class that is declared abstract means it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
Abstract Class Definition Rules:
  1. Abstract classes cannot be instantiated directly.
  2. Abstract classes may be defined with any number, including zero, of abstract and non-abstract methods.
  3. Abstract classes may not be marked as private or final.
  4. An abstract class that extends another abstract class inherits all of its abstract methods as its own abstract methods.
  5. The first concrete class that extends an abstract class must provide an implementation for all of the inherited abstract methods.
Example :
public class AbstractClassCompleteExample {

    public static void main(String[] args) {
         Animals animals = new Cat();
         animals.sound();
  
         animals = new Dog();
         animals.sound();
    }
}

abstract class Animals{
    private String name;
 
    // All kind of animals eat food so make this common to all animals
    public void eat(){
         System.out.println(" Eating ..........");
    }
 
    // The aninals make different sounds. They will provide their own implementation
    abstract void sound(); 
}

class Cat extends Animals{

    @Override
    void sound() {
        System.out.println("Meoww Meoww ........");
    }
}

class Dog extends Animals {

    @Override
    void sound() {
         System.out.println("Woof Woof ........");
    }
}

2. Abstract Method

An abstract method is a method that is declared without an implementation.
Abstract Method Definition Rules:
  1. Abstract methods may only be defined in abstract classes.
  2. Abstract methods may not be declared private or final.
  3. Abstract methods must not provide a method body/implementation in the abstract class for which is it declared.
  4. Implementing an abstract method in a subclass follows the same rules for overriding a method. 
Example: The below AbstractShape class contains two abstract methods - draw() and moveTo();
abstract class AbstractShape{
    abstract void draw();
    abstract void moveTo(double deltaX, double deltaY);
}

3. If a class includes abstract methods, then the class itself must be declared abstract

Example:
public abstract class AbstractClassExample {
   // declare fields
   // declare nonabstract methods
   abstract void abstractMethod();
}

4. When an abstract class is subclassed

The subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

For example :
abstract class AbstractShape{
    abstract void draw();
}

//The abstract method draw in type Shape can only be defined by an abstract class
abstract class Shape extends AbstractShape{

    @Override
    abstract void draw();
    
    /*@Override
    void draw() {
        // TODO Auto-generated method stub
        
    }*/
}

6. When an Abstract Class Implements an Interface

When we create the Java class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface's methods, provided that the class is declared to be abstract.

For example:
 interface A {
    void a();

    void b();

    void c();

    void d();
}

// The abstract class can also be used to provide some implementation of the interface. 
//In such case, the end user may not be forced to override all the methods of the interface.
abstract class B implements A {
    public void c() {
        System.out.println("I am c");
    }
}

class M extends B {
    public void a() {
        System.out.println("I am a");
    }

    public void b() {
        System.out.println("I am b");
    }

    public void d() {
        System.out.println("I am d");
    }
}

class Test5 {
    public static void main(String args[]) {
        final A a = new M();
        a.a();
        a.b();
        a.c();
        a.d();
    }
}
Let's see some examples of using Abstract classes in real projects.

Usage of abstract classes in Real-world Examples

Employee, Contractor, and FullTimeEmployee Example

In this example, we create an abstract Employee class and which contains abstractcalculateSalary () method. Let the subclasses extend Employee class and implementcalculateSalary() method.

Let's create Contractor and FullTimeEmployee classes as we know that the salary structure for a contractor and full-time employees are different so let these classes to override and implement a calculateSalary() method.

Let's write source code by referring above class diagram.

Step 1: Let's first create the abstract superclass named an Employee. Let's define a method called calculateSalary() as an abstract method in this abstract Employee class. So the method is abstract and we can leave the implementation of this method to the inheritors of the Employee class.
public abstract class Employee {
 
    private String name;
    private int paymentPerHour;
 
    public Employee(String name, int paymentPerHour) {
         this.name = name;
         this.paymentPerHour = paymentPerHour;
    }
 
    public abstract int calculateSalary();
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPaymentPerHour() {
       return paymentPerHour;
    }
    public void setPaymentPerHour(int paymentPerHour) {
        this.paymentPerHour = paymentPerHour;
    }
}
Step 2: The Contractor class inherits all properties from its parent Employee but have to provide its own implementation to calculateSalary() method. In this case, we multiply the value of payment per hour with given working hours.
public class Contractor extends Employee {
 
    private int workingHours;
    public Contractor(String name, int paymentPerHour, int workingHours) {
        super(name, paymentPerHour);
        this.workingHours = workingHours;
    }
    @Override
    public int calculateSalary() {
        return getPaymentPerHour() * workingHours;
    }
}
Step 3: The FullTimeEmployee also has its own implementation of calculateSalary() method. In this case, we just multiply by a constant value of 8 hours.
public class FullTimeEmployee extends Employee {
    public FullTimeEmployee(String name, int paymentPerHour) {
        super(name, paymentPerHour);
    }
    @Override
    public int calculateSalary() {
        return getPaymentPerHour() * 8;
    }
}
Step 4 : Let's create a test class to test the Abstract class.
public class AbstractClassDemo {

    public static void main(String[] args) {

        Employee contractor = new Contractor("contractor", 10, 10);
        Employee fullTimeEmployee = new FullTimeEmployee("full time employee", 8);
        System.out.println(contractor.calculateSalary());
        System.out.println(fullTimeEmployee.calculateSalary());
    }
}

Summary

Let's summarize what we have discussed in this article:
  • An abstract class is a class that is declared with abstract keyword.
  • An abstract method is a method that is declared without an implementation.
  • An abstract class may or may not have all abstract methods. Some of them can be concrete methods
  • A method defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either make subclass itself abstract.
  • Any class that contains one or more abstract methods must also be declared with abstract keyword.
  • There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.
  • An abstract class can have parameterized constructors and default constructor is always present in an abstract class.
Learn complete Core Java at Java Tutorial | Learn Java Programming with Examples

Comments