Abstract class in Java

CodingTute

Java

Java programming language provides developers with various features, one of which is the abstract class concept. An abstract class serves as a base for creating other classes, but it cannot be instantiated itself. Many developers find abstract classes confusing; however, once understood, they provide exceptional benefits.

In this article, we will learn about the definition, declaration, implementation, and differences between abstract classes and interfaces in Java. We will also explore when to use them and take an example to better understand how to work with them.

Basics of Java Classes

Before diving into abstract classes, we must understand the basics of Java classes. A class is a blueprint or template for creating objects, instances of that class. The class defines the properties and behaviors of the object that the instance or object should possess. When you define a class, you establish a new type that can be utilized to create objects.

The following are some basic features of a Java class:

  • Classes have constructors that create objects.
  • Fields store the state of objects, while methods define their behavior.
  • Each class has its own methods, fields, and constants.

What is Abstract Class in Java

An abstract class is a class that cannot be instantiated but is used as a base class for other classes. It acts as a skeleton for any derived classes that extend it. An abstract class may include both abstract and non-abstract methods. It is intended to provide a set of default implementations that can be inherited and modified according to the specificities of the derived class.

Declaring an Abstract Class

A Java abstract class can be declared by preceding the class keyword with the keyword abstract. For example:

public abstract class Animal {
    public abstract void sound();
}

The above code declares an abstract class named Animal with an abstract method called sound(). Note that abstract classes cannot be instantiated directly; they must be extended by a concrete (non-abstract) class.

What is Abstract Method in Java

An abstract method is a method that is declared but does not have an implementation. An abstract method’s signature ends in a semicolon rather than a block.

public abstract void sound();

The above code defines an abstract method, sound(), without providing any definitions for it.

Implementing Abstract Classes and Methods

Any derived class that extends an abstract class must implement all abstract methods of the parent abstract class; otherwise, it becomes an abstract class itself. Here’s how you implement an abstract class:

public class Dog extends Animal {
    public void sound() {
        System.out.println("Woof!");
    }
}

In this code snippet, the Dog class extends the Animal abstract class and provides a definition for the sound() method. Because it provides a definition for all abstract methods of its parent abstract class, it is known as a concrete class.

Constructors in Abstract Classes

Abstract classes can still contain constructors, unlike interfaces. Constructors are used to initialize variables or values when creating objects. If a subclass has concrete constructors, it must call one of the constructors from its superclass in its constructor using the super() keyword.

public abstract class Animal {
    private int age;

    public Animal(int age) {
        this.age = age;
    }

    // abstract method
    public abstract void sound();
}

In this code snippet, the Animal class contains a constructor that initializes its age member and an abstract method called sound().

Benefits of Using Abstract Classes

Here are some benefits of using abstract classes in Java:

  • Encapsulation: Abstract classes allow us to hide implementation details from users by providing only relevant methods and properties.
  • Default Behavior: They provide default implementations for inherited classes without repeating the code.
  • Code Reuse: Multiple derived classes can use the common functionality defined in the abstract class.
  • Abstraction: Abstract classes define a clear hierarchy of classes and their relationship. They provide a way to implement abstraction by hiding the implementation details.

Drawbacks of Using Abstract Classes

Using abstract classes also comes with some disadvantages such as:

  • Inflexibility: Once implemented, it is hard to change the entire hierarchy because of the tight coupling between the base class and implementing classes.
  • Coupling: Since abstract classes serve as a base for other classes, they introduce tight coupling which makes the system more difficult to maintain and modify.

Differences Between Abstract Classes and Interfaces

Although abstract classes and interfaces share some similarities, there are significant differences between them. Here are some of the differences:

  • Implementation: Abstract classes have constructors, fields, and methods with or without implementation, while interfaces cannot contain any implementation for the methods.
  • Constructors: Abstract classes include constructors, while interfaces have none.
  • Multiple Inheritance: A class can extend only one abstract class, but it can implement multiple interfaces.
  • Accessibility Convention: By convention, methods declared in an interface should be public, while those declared in an abstract class can be either protected (or package-private) or public.

When to Use Abstract Classes?

Consider using an abstract class when you want to:

  • Provide a template for a group of similar classes.
  • Ensure that derived classes conform to a standard interface.
  • Define a common implementation for all derived classes.
  • Use inheritance to avoid duplicate code.

Example of Abstract Class in Java

To understand abstract class in more detail, let us take a simple example of the parent Person class that has two child classes named Student and Teacher.

// Parent Class
public abstract class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Abstract Method
    public abstract void display();

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

// Derived Class
public class Student extends Person{
    private String college;

    public Student(String name,int age,String college){
        super(name, age);
        this.college=college;
    }

    // Overriding the display method
    @Override
    public void display() {
        System.out.println("Name: "+ super.getName());
        System.out.println("Age:"+ super.getAge());
        System.out.println("College:"+college);
    }
}

// Derived Class 
public class Teacher extends Person{
    private String subject;

    public Teacher(String name,int age,String subject){
        super(name, age);
        this.subject=subject;
    }

    // Overriding the display method
    @Override
    public void display() {
        System.out.println("Name: "+ super.getName());
        System.out.println("Age:"+ super.getAge());
        System.out.println("Subject taught:"+subject);
    }
}

In this example, when we create an object for either the Student or Teacher class, the display() method is called which is defined in their respective classes. Yet, both student and teacher classes have inherited the behavior of the Person class.

Conclusion

Java’s Abstract Class is a powerful feature that provides a way to define default implementations while allowing customizations in the derived classes. Although it may seem complex at first, abstraction can help to create more organized and reusable code.

In this article, we learned the basics of Java classes and abstract classes, including their definition and implementation, advantages, disadvantages, and differences between interfaces and abstract classes. We also took an example to better understand how abstract classes work.

Frequently Asked Questions

What is the difference between an abstract class and an interface in Java?

Implementation: An abstract class can contain concrete methods while interfaces cannot.
Multiple Inheritance: A class cannot inherit from multiple abstract classes but can implement multiple interfaces.
Constructors: An abstract class can have constructors while an interface cannot.
Accessibility Convention: By convention, methods declared in an interface should be public, while those declared in an abstract class can be either protected (or package-private) or public.

Can an abstract class have no abstract methods?

Yes, an abstract class can have both abstract and non-abstract methods. It provides a default implementation for derived classes that do not wish to override the non-abstract methods.

What is an abstract method?

An abstract method is a method without a body, marked with the abstract keyword. It must be overridden by any class that extends the abstract class.

Can an abstract class have a static method?

Yes, an abstract class can have a static method. However, as abstract classes cannot be directly instantiated, static methods cannot be called using an abstract class’s reference.

Can we create object of abstract class in Java?

No, we cannot create an object of an abstract class in Java. An abstract class is a class that is not complete, meaning it cannot be instantiated directly as it may contain abstract methods which have no implementation. It serves as a base for other classes to inherit from and provide the implementation for its methods. Therefore, we must first create a concrete class that extends the abstract class, then create an object of the concrete class.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.