Tutorial

Abstract Class in Java

Published on August 3, 2022
author

Pankaj

Abstract Class in Java

Abstract class in Java is similar to interface except that it can contain default method implementation. An abstract class can have an abstract method without body and it can have methods with implementation also. abstract keyword is used to create a abstract class and method. Abstract class in java can’t be instantiated. An abstract class is mostly used to provide a base for subclasses to extend and implement the abstract methods and override or use the implemented methods in abstract class.

Abstract Class in Java

abstract class in java, java abstract class example Here is a simple example of an Abstract Class in Java.

package com.journaldev.design;

//abstract class
public abstract class Person {
	
	private String name;
	private String gender;
	
	public Person(String nm, String gen){
		this.name=nm;
		this.gender=gen;
	}
	
	//abstract method
	public abstract void work();
	
	@Override
	public String toString(){
		return "Name="+this.name+"::Gender="+this.gender;
	}

	public void changeName(String newName) {
		this.name = newName;
	}	
}

Notice that work() is an abstract method and it has no-body. Here is a concrete class example extending an abstract class in java.

package com.journaldev.design;

public class Employee extends Person {
	
	private int empId;
	
	public Employee(String nm, String gen, int id) {
		super(nm, gen);
		this.empId=id;
	}

	@Override
	public void work() {
		if(empId == 0){
			System.out.println("Not working");
		}else{
			System.out.println("Working as employee!!");
		}
	}
	
	public static void main(String args[]){
		//coding in terms of abstract classes
		Person student = new Employee("Dove","Female",0);
		Person employee = new Employee("Pankaj","Male",123);
		student.work();
		employee.work();
		//using method implemented in abstract class - inheritance
		employee.changeName("Pankaj Kumar");
		System.out.println(employee.toString());
	}

}

Note that subclass Employee inherits the properties and methods of superclass Person using inheritance in java. Also notice the use of Override annotation in Employee class. Read more for why we should always use Override annotation when overriding a method.

Abstract class in Java Important Points

  1. abstract keyword is used to create an abstract class in java.
  2. Abstract class in java can’t be instantiated.
  3. We can use abstract keyword to create an abstract method, an abstract method doesn’t have body.
  4. If a class have abstract methods, then the class should also be abstract using abstract keyword, else it will not compile.
  5. It’s not necessary for an abstract class to have abstract method. We can mark a class as abstract even if it doesn’t declare any abstract methods.
  6. If abstract class doesn’t have any method implementation, its better to use interface because java doesn’t support multiple class inheritance.
  7. The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class.
  8. All the methods in an interface are implicitly abstract unless the interface methods are static or default. Static methods and default methods in interfaces are added in Java 8, for more details read Java 8 interface changes.
  9. Java Abstract class can implement interfaces without even providing the implementation of interface methods.
  10. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.
  11. We can run abstract class in java like any other class if it has main() method.

That’s all for an abstract class in Java. If I missed anything important, please let us know through comments.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 14, 2013

Nice tutorial, I think you have covered everything about abstract classes and methods. Please provide some difference between abstract class and interface.

- Amit

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 2, 2016

Methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behaviour. Variables declared in a Java interface are by default final. An abstract class may contain non-final variables. Members of a Java interface are public by default. A Java abstract class can have the usual flavours of class members like private, protected, etc. A Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. A Java class can implement multiple interfaces but it can extend only one abstract class. Happy Learning :)

- Aliasger Motiwala

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 13, 2014

    There are two classes person and Employee. You have created the object of person class. Is it ok? and where is ‘changeName’ method?

    - Kapil

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 8, 2014

      This is is not showing parameter value . i have use Person student= new Employee(“Deepak”,“Male”,20);

      - deepak

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 7, 2014

        1. abstract class can’t be instantiated 2. abstract class can contain definition of function with respect to these features, my question is— can we call those function which are defined in abstract class by reference of that class? if yes then why and how?

        - Firoj Mujawar

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 7, 2014

        You should have a concrete class extending the abstract class and provide implementation of abstract methods, you can also have anonymous class implementation. After that it’s just inheritance.

        - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 8, 2014

        abstract class MyAbstractClass { public void definedMethod() { System.out.println(“This is defined in Abstract Base Class”); } public abstract void declaredMethod(); } class SubClass extends MyAbstractClass { public void declaredMethod() { System.out.println(“This is defined in Subclass of Abstract”); } } public class AbstractMethodCall { public static void main(String asds[]) { MyAbstractClass abs=new SubClass(); abs.declaredMethod(); abs.definedMethod(); // here is the problem. how this is done?? } }

        - Firoj Mujawar

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 3, 2015

        There is no problem in fact. SubClass extends MyAbstractClass. Hence, definedMethod() will also be available in MyAbstractClass. It calls the definedMethod() method and prints “This is defined in Abstract Base Class”

        - Prashanth

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 10, 2015

          can we override a non abstract method of abstract class . If yes then what is the use of making a method abstract in abstract class.

          - vishnu

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            April 4, 2015

            Abstract class can contain Constructor, if we cannot create an instance what is the use of this constructor.

            - Raghuveer Kurdi

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            April 5, 2015

            Yes, Abstract classes can have constructors unlike Interfaces. However we cannot directly instantiate an Abstract class to create an instance. The purpose of the Abstract class constructors (we can have multiple abstract class constructors with different arguments) is to initialize the final variables from subclasses (kind of lazy initialization)

            - Vishnu Prakash

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 17, 2016

              To Achieve Constructor Chaining Abstract Class Should have Constructor, though Object Cant be Created for it. Every Java Class Will inherit From Object class… So Even Abstract Class Will inherit From Object Class. So If There is Inheritance between Classes then Constructor Chaining is Mandatory!! Constructor Chaining means Sub Class Constructor Calling its Immediate Super Class Constructor.

              - Raj

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 29, 2015

                Abstract class can’t be instantiated. It is wrong what about anonymous class.

                - manish

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                March 22, 2016

                No. Abstract Classes cannot be instantiated. Let us say we have got an abstract class absClass with one unimplemented abstract method doSayHello. When we implement doSayHello method in the curly brackets, we are doing it under the pretence that we are extending an unnamed class but not by instantiating the abstract class itself. absClass ab = new absClass(){ @Override public void doSayHello() { System.out.println(“Hello World !”); } }; ab.doSayHello(); // prints “Hello World !”

                - Yunus Atheist

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                October 23, 2018

                Nice example for creating object for abstract class

                - kalanidhi

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  September 9, 2019

                  Isn’t this example creating an instance of absClass?

                  - Frank Silano

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    November 23, 2015

                    Hi Pankaj, Can u please tell me where we can use interfaces and abstract classes in realtime,could you please give me in realtime example.

                    - Rajesh

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      January 7, 2016

                      can i have more day to day life examoles on abstract class…

                      - shaurya gaurav mehta

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 2, 2016

                      public interface LoginAuth{ public String encryptPassword(String pass); public void checkDBforUser(); } Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods: public class DBMySQL implements LoginAuth{ // Needs to implement both methods } public class DBOracle implements LoginAuth{ // Needs to implement both methods } public class DBAbc implements LoginAuth{ // Needs to implement both methods } But what if encryptPassword() is not database dependent, and it’s the same for each class? Then the above would not be a good approach. Instead, consider this approach: public abstract class LoginAuth{ public String encryptPassword(String pass){ // Implement the same default behavior here // that is shared by all subclasses. } // Each subclass needs to provide their own implementation of this only: public abstract void checkDBforUser(); } Now in each child class, we only need to implement one method - the method that is database dependent. Tried my best to make you understand. Happy Learning :)

                      - Aliasger Motiwala

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        January 25, 2016

                        i need to submit this morning. i have working out my self but i am unable to define it. define an interface that consists of methods that can operate on classes employee and student

                        - odelami emmanuel

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          March 27, 2016

                          Hey could you please explain that , How do you use “employee.changeName(“Pankaj Kumar”);” ? What is changeName ?

                          - lahiru

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            June 15, 2016

                            I feel like the Person, Employee relationship is better represented by an interface rather than an abstract class because a Person can be an Employee but it is not a necessity. A person can be more than one thing therefore A Person should implement an interface called Employee because they can also be something else like a manager or a supervisor.

                            - Stanley

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            June 16, 2016

                            Every Employee "is a " Person. So Person has to be superclass. It’s your choice whether you want to have it abstract class or interface. With Java 8 interface default and static methods, there is not much difference between abstract class and interface.

                            - Pankaj

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              June 20, 2016

                              Why Abstract Class is used in Java? I want to know the sole purpose of Abstract Class other than its providing Data hiding and forces the programmer to implement all the methods in Abstract class.

                              - Yoganathan

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              June 20, 2016

                              you can have default implementation and abstract methods that you want all the implementation classes to implement. However with Java 8 default methods in interfaces, Interface and Abstract class are almost same.

                              - Pankaj

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 18, 2017

                                Abstract class points super

                                - Siva

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  August 26, 2016

                                  Confused. Where does “changeName” come from??

                                  - James

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  August 27, 2016

                                  While doing some editing, I mistakenly deleted changeName method from Person class, I have corrected it.

                                  - Pankaj

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    February 11, 2018

                                    when to use abstract class and when to use interface?

                                    - salman

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    June 3, 2020

                                    if you want to object + abstraction then go for abstract class. if you want to only abstraction then go for interface.

                                    - Deepak Tiwari

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      February 25, 2018

                                      we can create a object for abstract class…

                                      - CHINTUL

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      March 7, 2018

                                      No … We can not create object of abstract class. It is anonymous object.

                                      - patil s

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        June 26, 2018

                                        As it has been mentioned clearly, an abstract class can’t be instantiated, we can not create an object of it.

                                        - Fravashi Kaustav

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          May 12, 2018

                                          where is the Encapsulation and polymorphism in oops concept?

                                          - nirmala

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            August 23, 2018

                                            It was a wonderful recap of what i learned java docs from various resources in internet. Thanks for covering entire picture of core java. God bless you!!

                                            - sathish

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              September 14, 2018

                                              Nice bro

                                              - Alwin

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                September 16, 2018

                                                Hi, Thank you in advace for yout awsome tutorials and topis. in the section of ‘Abstract class in Java Important Points’. point number 5 I guess is not correct. because to have an abstract method, its class must be abstract also. If I`m wrong it would be greate to clear me. Thanks

                                                - Morteza

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                September 16, 2018

                                                You got it another way around, it says “It’s not necessary to have the abstract class to have abstract method.” That means we can mark a class as abstract even if it doesn’t have any abstract methods.

                                                - Pankaj

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  September 23, 2018

                                                  The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class. On a similar note, If Class3 extends abstract Class2 and abstract Class2 extends abstract Class1, then Class3 should implement all the abstract methods of Class1 and Class2. Class 2 need not implement methods of Class1 since Class2 is also abstract.

                                                  - Praveen

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  February 6, 2019

                                                  Yes, if it class3 is not an abstract class.

                                                  - VIJAY

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    September 24, 2018

                                                    you ain’t mentioned what’s the use of it.

                                                    - Deepak gupta

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    February 18, 2019

                                                    …“10. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.” Did you even read the article?

                                                    - Kenneth

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      March 2, 2019

                                                      Does abstract class contains Constructor? If yes, then what is the use of it?

                                                      - Bhagyashri Chaudhari

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      March 12, 2019

                                                      Abstract classes cannot be instantiated, so they do not need constructors.

                                                      - Frank

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        March 16, 2019

                                                        abstarct class have a constructer for instantiate child class object .

                                                        - umakant chaudhary

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          March 6, 2019

                                                          what is the main role of abstract class in java?

                                                          - aryan

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          July 18, 2019

                                                          abstract class mainly use to restrict the object creation of that class.

                                                          - Ketul Chauhan

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            July 30, 2019

                                                            if you want to object + abstraction then go for abstract class. if you want to only abstraction then go for interface.

                                                            - Pulkit Sharma

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              March 11, 2021

                                                              basically it is an Partially implemented class means some methods have body where some have only Signature(Only declaration).

                                                              - ancd

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                March 31, 2019

                                                                Respected admin, i would like to point out an improvement in point number 5 of the *Important points* written at the end, i believe the correct statement should be : It’s not necessary FOR AN abstract class to have abstract method. We can mark a class as abstract even if it doesn’t declare any abstract methods. instead of It’s not necessary TO HAVE abstract class to have abstract method. We can mark a class as abstract even if it doesn’t declare any abstract methods… It’s really ambiguous otherwise . i hope the admin would act promptly.

                                                                - Hissaan

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                April 1, 2019

                                                                Sorry for silly grammar error, I have fixed it.

                                                                - Pankaj

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                April 6, 2019

                                                                happy to hear such a prompt response, keep going !

                                                                - Hissaan

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  May 28, 2019

                                                                  Important points are easy to understand about the abstract class thank you for your explanation ;)

                                                                  - Venkatesh

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    June 26, 2019

                                                                    By using the static keyword we can access the concrete methods in the abstract class. Can any one tell without using the static how can we access the concrete methods in the abstract class?

                                                                    - Udaya Bhargavi

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    October 28, 2019

                                                                    We can access the concrete class’s method by making the class object. For example, public class ConcreteClass{ public void fun(){ } } public abstract class AbstractClass{ //Constructor public AbstractClass(){ ConcreteClass obj = new ConcreteClass(); obj.fun(); } }

                                                                    - Umar Bilal

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      September 11, 2019

                                                                      Can u please explain one Real World Use Case for Abstract class and abstract Method b

                                                                      - Anshul Daksh

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      March 4, 2020

                                                                      A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. It might also provide an abstract method called “Is Dead” that, when called, will tell you if the animal has died. Since Is Dead is abstract, each animal must implement it…

                                                                      - singhtinku

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        April 8, 2020

                                                                        please explain me about abstract with easy example because i didn’t it in better way. i request you and please also explain me all those points in better ways

                                                                        - ANJALI THAKUR

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          September 26, 2021

                                                                          how can we invoke any static method from abstract class?

                                                                          - Priyanka

                                                                            Try DigitalOcean for free

                                                                            Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                            Sign up

                                                                            Join the Tech Talk
                                                                            Success! Thank you! Please check your email for further details.

                                                                            Please complete your information!

                                                                            Become a contributor for community

                                                                            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                            DigitalOcean Documentation

                                                                            Full documentation for every DigitalOcean product.

                                                                            Resources for startups and SMBs

                                                                            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                            Get our newsletter

                                                                            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                            New accounts only. By submitting your email you agree to our Privacy Policy

                                                                            The developer cloud

                                                                            Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                            Get started for free

                                                                            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                            *This promotional offer applies to new accounts only.