BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Abstract Class in Java with example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

A class that is declared using “abstract” keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-abstract class) cannot have abstract methods. In this guide we will learn what is a abstract class, why we use it and what are the rules that we must remember while working with it in Java.

An abstract class can not be instantiated, which means you are not allowed to create an object of it. Why? We will discuss that later in this guide.

Why we need an abstract class?

Lets say we have a class Animal that has a method sound() and the subclasses(see inheritance) of it like Dog, Lion, Horse, Cat etc. Since the animal sound differs from one animal to another, there is no point to implement this method in parent class. This is because every child class must override this method to give its own implementation details, like Lion class will say “Roar” in this method and Dog class will say “Woof”.

So when we know that all the animal child classes will and should override this method, then there is no point to implement this method in parent class. Thus, making this method abstract would be the good choice as by making this method abstract we force all the sub classes to implement this method( otherwise you will get compilation error), also we need not to give any implementation to this method in parent class.

Since the Animal class has an abstract method, you must need to declare this class abstract.

Now each animal must have a sound, by making this method abstract we made it compulsory to the child class to give implementation details to this method. This way we ensures that every animal has a sound.

Abstract class Example

//abstract parent class
abstract class Animal{
   //abstract method
   public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

   public void sound(){
	System.out.println("Woof");
   }
   public static void main(String args[]){
	Animal obj = new Dog();
	obj.sound();
   }
}

Output:

Woof

Hence for such kind of scenarios we generally declare the class as abstract and later concrete classes extend these classes and override the methods accordingly and can have their own methods as well.

Abstract class declaration

An abstract class outlines the methods but not necessarily implements all the methods.

//Declaration using abstract keyword
abstract class A{
   //This is abstract method
   abstract void myMethod();

   //This is concrete method with body
   void anotherMethod(){
      //Does something
   }
}

Rules

Note 1: As we seen in the above example, there are cases when it is difficult or often unnecessary to implement all the methods in parent class. In these cases, we can declare the parent class as abstract, which makes it a special class which is not complete on its own.

A class derived from the abstract class must implement all those methods that are declared as abstract in the parent class.

Note 2: Abstract class cannot be instantiated which means you cannot create the object of it. To use this class, you need to create another class that extends this this class and provides the implementation of abstract methods, then you can use the object of that child class to call non-abstract methods of parent class as well as implemented methods(those that were abstract in parent but implemented in child class).

Note 3: If a child does not implement all the abstract methods of abstract parent class, then the child class must need to be declared abstract as well.

Do you know? Since abstract class allows concrete methods as well, it does not provide 100% abstraction. You can say that it provides partial abstraction. Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user.

Interfaces on the other hand are used for 100% abstraction (See more about abstraction here).
You may also want to read this: Difference between abstract class and Interface in Java

Why can’t we create the object of an abstract class?

Because these classes are incomplete, they have abstract methods that have no body so if java allows you to create object of this class then if someone calls the abstract method using that object then What would happen?There would be no actual implementation of the method to invoke.
Also because an object is concrete. An abstract class is like a template, so you have to extend it and build on it before you can use it.

Example to demonstrate that object creation of abstract class is not allowed

As discussed above, we cannot instantiate an abstract class. This program throws a compilation error.

abstract class AbstractDemo{
   public void myMethod(){
      System.out.println("Hello");
   }
   abstract public void anotherMethod();
}
public class Demo extends AbstractDemo{

   public void anotherMethod() { 
        System.out.print("Abstract method"); 
   }
   public static void main(String args[])
   { 
      //error: You can't create object of it
      AbstractDemo obj = new AbstractDemo();
      obj.anotherMethod();
   }
}

Output:

Unresolved compilation problem: Cannot instantiate the type AbstractDemo

Note: The class that extends the abstract class, have to implement all the abstract methods of it, else you have to declare that class abstract as well.

Abstract class vs Concrete class

A class which is not abstract is referred as Concrete class. In the above example that we have seen in the beginning of this guide, Animal is a abstract class and Cat, Dog & Lion are concrete classes.

Key Points:

  1. An abstract class has no use until unless it is extended by some other class.
  2. If you declare an abstract method in a class then you must declare the class abstract as well. you can’t have abstract method in a concrete class. It’s vice versa is not always true: If a class is not having any abstract method then also it can be marked as abstract.
  3. It can have non-abstract method (concrete) as well.

I have covered the rules and examples of abstract methods in a separate tutorial, You can find the guide here: Abstract method in Java
For now lets just see some basics and example of abstract method.
1) Abstract method has no body.
2) Always end the declaration with a semicolon(;).
3) It must be overridden. An abstract class must be extended and in a same way abstract method must be overridden.
4) A class has to be declared abstract to have abstract methods.

Note: The class which is extending abstract class must override all the abstract methods.

Example of Abstract class and method

abstract class MyClass{
   public void disp(){
     System.out.println("Concrete method of parent class");
   }
   abstract public void disp2();
}

class Demo extends MyClass{
   /* Must Override this method while extending
    * MyClas
    */
   public void disp2()
   {
       System.out.println("overriding abstract method");
   }
   public static void main(String args[]){
       Demo obj = new Demo();
       obj.disp2();
   }
}

Output:

overriding abstract method
❮ PreviousNext ❯

Top Related Articles:

  1. Java – Static Class, Block, Methods and Variables
  2. OOPs concepts – What is Aggregation in java?
  3. Multithreading in java with examples
  4. Final Keyword In Java – Final variable, Method and Class
  5. Inheritance in Java With Examples

Tags: Java-OOPs

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. digbijay mohanty says

    March 11, 2014 at 6:08 PM

    still not clear what is the practical applicability of abstract method. please suggest me.

    Reply
    • KV Iyer says

      April 10, 2014 at 3:01 PM

      Hi Digbijay,

      Abstract method is just a signature without any implementation block inside.Abstract method must be overridden in the subclasses to make use for the object to invoke.
      An Abstract Method is just a prototype for the method with the following attributes:-
      1) A return type
      2) A name
      3) A list of Parameters
      4) A throws clause which is optional

      Example:- public abstract int salary(int empNo)

      Hope this helps.

      Reply
  2. sunil says

    July 26, 2014 at 5:34 PM

    Can a abstract class have a constructor ????
    and if yes, why ???
    and if No, why ???

    Reply
    • hamid says

      August 1, 2014 at 7:04 AM

      Dear Sunil ,

      No !! because constructor is called when the object is created . but abstact method does not have an instance so ,it is not possible to call a abstract constructor .

      Reply
      • Ankit Fulzele says

        August 7, 2015 at 8:41 AM

        Dear Hamid,

        I guess you have mistaken the concept there need to make correction in our response .

        Abstract class can also have constructor. Even though we cannot instantiate abstract class the default constructor is always there. Either we can provide it explicitly or it is provided by Java. The reason why it is there because in the concept of inheritance you have to maintain class hierarchy, means if your class extends abstract class then the same abstract class will become super class for your extending class and remember when you have constructor of your class then first line of your constructor is always super class constructor and this is the time when your abstract class constructor get called

        hope you are clear now !

        Reply
        • Mark Anthony says

          August 20, 2015 at 7:16 AM

          Hello Ankit Fulzele,

          Is it possible to instantiate an abstract class ?
          For me, it is if the abstract class has derived a concrete class, which will be like this:
          identifier = new ;

          Am I right ?

          More thanks,
          Mark

          Reply
        • Mayur says

          February 1, 2017 at 7:59 AM

          Later when we create object of intended class it will implicitly call the constructor of abstract class.. when the constructor will be called does this mean object of that class have to be created?

          Reply
      • Abhishek Singh says

        December 3, 2015 at 2:23 PM

        Dear Hamid! In abstract class can also have constructor because constructors are not used for creating object, constructors are used to initialize the data members of a class and Abstract class can also have data member and for initialize the data member of abstract class need a constructor if we did not provide the constructor then jvm supply the 0-param or default constructor for initializing the data member.

        Reply
    • Nishita Tiwary says

      September 24, 2017 at 4:49 AM

      abstract classes can have constructors..though abstract classes cannot be instantiated..that means..we cannot create objects of an abstract class..but still abstract class can have constructors..and this constructor can be called by a subclass(which inherits an abstract class) by using the super keyword.

      Reply
  3. Pradeep kumar Rajak says

    March 29, 2016 at 12:34 PM

    You can try to publish a book of your website after proper legal advising.
    Contents are very good in your website.

    Reply
  4. Uday says

    July 7, 2016 at 5:14 PM

    how can you access concrete methods in abstract class if you cannot create an object of an abstract class. like in given example how will i run disp1 method? what changes should be done in the code?

    Reply
    • Aakash talreja says

      August 18, 2016 at 2:42 PM

      Abstract class can have concrete method,& yes we cannot create object,but if you extend ur abstract class by any other class so through inheritance child get all the method(concrete method also of parent class) here dynamic polymorphism is achieved by using reference of parent u can call that concrete method of parent class,& if u dont want that parent method just override that concrete method of that parent class in child class.

      Reply
  5. Alex says

    July 14, 2016 at 1:15 PM

    Uday unfortunately you cannot access the concrete methods of an abstract class unless you extend the class. An abstract class is actually almost useless on their own. You can see an abstract class like a lazy student who has to be told to read his books; if he doesn’t get told, he won’t be able to read his books. Telling the student is now analogous to extending the abstract class and the student then reading his books is analogous to the execution of the concrete methods if you like.

    Reply
  6. Shawon Shurid says

    November 27, 2016 at 10:20 PM

    Do we need type casting for Abstract class?
    why protected constructors are used in Abstract class?

    Reply
  7. sham says

    December 13, 2016 at 9:16 PM

    Why does one needs abstract class ? Animal class example has been given here. But can someone , please give me practical example where this is useful. If I am writing a java application, when should I stop writing all the logica in concrete class and start using the abstract class concept

    Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap