Abstract Classes and Abstract Methods in Java

Abstract Classes and Abstract Methods in Java

In this article, I am going to discuss Abstract Classes and Abstract Methods in Java with Examples. Please read our previous where we discussed Abstraction in Java with Examples. At the end of this article, you will understand what are Abstract Classes and Abstract Methods and its need as well as when and how to implement this in Java Applications with Examples.

Note: A method that does not have a body is called an abstract method and the class that is declared by using the abstract keyword is called an abstract class. If a class contains an abstract method, then it must be declared as abstract.

What is the abstract class in java?

A class that is declared by using the abstract keyword is called an abstract class in java. It is a partially implemented class used for developing some of the operations of an object which are common for all next level subclasses. So it contains both abstract methods, concrete methods including variables, blocks, and constructors.

It is always created as a superclass next to the interface in the object inheritance hierarchy for implementing common operations from the interface. An abstract class may or may not have abstract methods. But if a class contains an abstract method then it must be declared as abstract.

What is Abstract Method in Java?

A method that does not have a body is called an abstract method in Java. It is declared with the modifier abstract. The following are the properties of the java abstract method,

  • It can only be used in an abstract class, and it does not have a body.
  • An abstract method contains a method signature, but no method body.
  • An abstract method is a method that is declared without implementation.
  • Instead of curly braces, an abstract method will have a semicolon (;) at the end.
  • A method-defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either making the subclass itself abstract.
Why method should have an abstract keyword if it does not have a body?

In a class, we are allowed only to define a class with a body. Since we are changing its default behavior (which means removing its body) it must have an abstract keyword in its prototype.

When a class should be declared abstract in Java?

A class should be declared as abstract

  1. If it has any abstract methods
  2. If it does not provide implementation to any of the abstract methods it inherited
  3. If it does not provide implementation to any of the methods of an interface.
When to use Abstract Methods in Java?

Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways. Often the subclasses are required to fulfill an interface, so the abstract superclass might provide several of the interface methods, but leave the subclasses to implement their own variations of the abstract methods. Abstract classes can be thought of as part-complete templates that make it easier to write a series of subclasses.

Rules of Abstract Class and Abstract Methods in Java:
Rule1:

If the method does not have a body it should be declared as abstract using the abstract modifier else it leads to CE: “missing method body or declared abstract

public class Example
{
    void m1(); //CE: missing method body or declared abstract
}

CE: missing method body or declared abstract

Rule2:

If a class has an abstract method it should be declared as abstract by using the keyword abstract else it leads to CE: class is not abstract and does not override the abstract method in the class.

public class Example
{
    abstract void m1();
}

CE: Example is not abstract and does not override abstract method m1() in Example. The correct syntax is given below.

abstract class Example
{
    abstract void m1();
}
Rule3:

If a class is declared as abstract it cannot be instantiated violation leads to compile-time Error.

abstract class Example
{
    abstract void m1();
    public static void main(String args[])
    {
        Example e = new Example();
    }
}

CE: Example is abstract, cannot be instantiated

Why abstract class cannot be instantiated?

Because it is not a fully implemented class so its abstract methods cannot be executed. If the compiler allows us to create an object for an abstract class we can invoke the abstract method using that object which cannot be executed by JVM at runtime. Hence to restrict calling abstract methods, the compiler does not allow us to instantiate an abstract class.

Who will provide implementation (body) for abstract methods?

Sub-class developers provide the body for abstract methods according to their business requirements. Basically in projects, abstract methods (method prototypes) are defined by superclass developers and they are implemented by sub-class developers. Implemented means providing the method body with logic.

Rule4:

The subclass of an abstract class should override all abstract methods or it should be declared as abstract else it leads to CE:

abstract class Example
{
    abstract void m1();
    abstract void m2();
}
class Sample extends Example
{
    void m1()
    {
        System.out.println("m1 method");
    }
}
Solutions:

Declare the class as abstract

abstract class Sample extends Example
{
     void m1 ()
     {
         System.out.println ("m1 method");
     }
}

Override both abstract methods

abstract class Sample extends Example
{
    void m1()
    {
        System.out.println("m1 method");
    }
    void m2()
    {
        System.out.println("m2 method");
    }
}
Can we declare an abstract method as static?

No, we are not allowed to declare an abstract method as static. It leads to CE: illegal combination of modifier abstract and static. If the compiler allows us to declare it as static, it can be invoked directly which cannot be executed by JVM at runtime. Hence to restrict calling abstract methods compiler does not allow us to declare an abstract method as static. For example

abstract class Example
{
    static abstract void m1();  //CE: illegal combination of modifier abstract 
    abstract void m2();		  // and static
}
Can we declare an abstract method as final?

No, because it should be allowed to override in subclasses. It leads to CE: illegal combination of modifier abstract and final. For example:

abstract class Example
{
    final abstract void m1();  //CE: illegal combination of modifier abstract 
    abstract void m2();		  // and final
}
Can we declare an abstract method as private?

No, because it should be inherited by subclasses. It leads to CE: illegal combination of modifier abstract and private. For example:

abstract class Example
{
    private abstract void m1(); //CE: illegal combination of modifier abstract 
    abstract void m2();		  // and private
}
Can we declare a concrete class as abstract in Java?

Yes, it is allowed. Defining a class as abstract is a way of preventing someone from instantiating a class that is supposed to be extended first. To ensure our class non-static members are only accessible via sub-class objects we should declare the concrete class as abstract.

Predefined concrete abstract classes are

  1. java.awt.Component
  2. javax.servlet.http.HttpServlet

let us see an example for a better understanding

A concrete class declared as abstract in Java
abstract class Example
{
    static void m1()
    {
        System.out.println("Example m1 method");
    }
    void m2()
    {
        System.out.println("Example m2 method");
    }
}

Calling concrete abstract members from normal class

class Sample
{
    public static void main(String args[])
    {
       Example.m1();
       Example e = new Example();//CE: cannot be instantiated class Example
       e.m2();
    }
}

Calling concrete abstract class members from sub-classes

class Sample extends Example
{
    public static void main(String args[])
    {
        Example.m1();
        Sample e = new Sample();
        e.m2();
    }
}

Output:
Example m1 method
Example m2 method

Difference Between Abstract class and Concrete class in Java:

Abstract Class in Java

Concrete Class in Java

A class declared with an abstract keyword which is a collection of abstract and non-abstract methods. A class that allows creating an instance of an object using the new keyword.
We cannot create an object using an abstract class. We can create an object using an abstract class.
An abstract class can have unimplemented methods. All methods in a concrete class are implemented.
When to use Abstract Classes and Abstract Methods in Java?

There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we want to create a superclass that only defines a generalization form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.

Consider a classic “Bank”, the base type is “Bank” and each bank has a Rate Of Interest, etc. From this, specific types of banks are derived (inherited)-SBI, HDFC, PNB, etc. – each of which may have additional characteristics and behaviors. For example, all banks may have different Rates of Interest. The type hierarchy embodies both the similarities and differences between the banks.

When to use Abstract Classes and Abstract Methods in Java

Sample Program for Abstract classes and Abstract Methods:
public class Main
{
     public static void main (String[]args)
     {
         Bank b;
         b = new SBI ();
         System.out.println ("SBI Rate of Interest is: " + b.getRateOfInterest () + " %");
         b = new PNB ();
         System.out.println ("PNB Rate of Interest is: " + b.getRateOfInterest () +" %");
     }
}

abstract class Bank
{
     abstract int getRateOfInterest ();
}
class SBI extends Bank
{
     int getRateOfInterest ()
     {
         return 7;
     }
}
class PNB extends Bank
{
     int getRateOfInterest ()
     {
        return 8;
     }
}
Output:

Abstract Classes and Abstract Methods in Java

What type of members we can define in an abstract class?

We can define all static and non-static members including constructors and also abstract methods.

Will abstract class members are created when a subclass object is created?

Yes, its non-static members get memory when its concrete sub-class object is created.

In the next article, I am going to discuss the Interface in Java with Examples. Here, in this article, I try to explain Abstract Classes and Abstract Methods in Java with Examples. I hope you enjoy this Abstract Classes and Abstract Methods in Java with Examples article. I would like to have your feedback. Please post your feedback, question, or comments on Abstract Classes and Abstract Methods in the Java article.

Leave a Reply

Your email address will not be published. Required fields are marked *