Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconAbstract Class in Java and Methods [With Examples]

Abstract Class in Java and Methods [With Examples]

Last updated:
17th Aug, 2022
Views
Read Time
17 Mins
share image icon
In this article
Chevron in toc
View All
Abstract Class in Java and Methods [With Examples]

In this article, I’ll share insights on abstraction in Java, focusing on abstract class in Java and methods. Abstraction simplifies complex systems by hiding the unnecessary details, letting us concentrate on what’s important. This not only makes our code cleaner but also more efficient. An abstract method in Java is a method that’s declared without an implementation in an abstract class using the abstract keyword. Understanding abstract methods is crucial because it leads us to grasp the essence of abstract classes. These classes cannot be instantiated on their own but provide a foundation for other classes to build upon, offering a blueprint for what methods they must implement. As a professional, mastering these concepts has been invaluable for my work, allowing me to design and implement more effective Java solutions. 

Check Out upGrad’s Java Bootcamp

Abstraction

One of the important concepts of Java is abstraction. It is the property by which the user is displayed with only the important details of a program. All the non-essential parts are kept hidden. The process can be explained through the example of an email. The senders send an email which gets delivered to the receiver. The only information known to the sender is that the email has been sent. The background process of sending the email is hidden from the users. Similar is the process in Object-Oriented Programming (OOP) where essential elements are displayed to the user while the non-essential parts are hidden. The user has no information about the implementation process, but only the functionality is known. This mechanism is known as the abstraction where only the essential characteristics of an object are shown while ignoring the other characteristics.

Check Out upGrad’s Advanced Certification in Cyber Security

Ads of upGrad blog

When you have to work with any method declaration in super class, you can do so by the declaration of any of the abstract methods in java as an abstract one.

Abstract class in java example can be best defined as a subclass responsibility without any implementation in super class. This is why any subclass needs to override the same for providing a method definition. The best way to understand abstract class in java example is to understand that abstraction will be achieved with the use of abstract classes as well as methods. In this tutorial, we will learn about abstract methods and their use in Java.

What Abstract Class Contains?

A class stands declared as abstract on using an abstract keyword. This may have zero or more methods that are abstract or non-abstract. We must extend what an abstract class contains and then implement the methods. Instantiation isn’t possible.

Check out our free courses related to software development.

Explore Our Software Development Free Courses

In Java, abstraction is achieved through the abstract classes and interfaces.

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Purpose and Use Cases of Abstract Classes in Java 

Abstract classes serve as the backbone for abstraction in Java, enabling a blueprint for other classes to follow. They embody a higher level of software design by allowing developers to define a set of methods that must be created within any of their subclass implementations. This concept is pivotal in object-oriented programming (OOP) because it helps manage complexity through a well-organized hierarchy of classes, fostering code reusability and scalability. 

The diagram above represents the fundamental concept of abstract classes in Java. Abstract classes, as depicted, serve as partial blueprints for other classes. They can declare both abstract methods, which are without implementation and must be overridden by subclasses, and concrete methods, which include implementation. This dual capability allows abstract classes to enforce a contract for subclasses to follow while providing shared functionality through concrete methods. 

Real-World Use Cases 

A practical example of using abstract classes is in the development of a graphics application. Consider an abstract class shape with a draw method (). Different shapes like Circles, rectangles, and triangles can extend this abstract class, each providing its own implementation of the draw() Method. This setup encapsulates the concept of a shape and ensures that each concrete shape adheres to a common interface, allowing for polymorphism and code reuse. 

Abstract class in Java

The keyword “abstract” is used for abstract classes and methods in Java. The abstract class has the abstract keyword in its declaration. 

The syntax of a Java abstract class is:

abstract class class_name

    {

            public abstract void the_abstractMethod();

            public void the_normalMethod()

            {

                    #body of the method

            }   

    }   

The above syntax shows that both normal and abstract methods can be contained in an abstract class.

Top Features Of Abstract Class

The top features of an abstract class are listed below-

  •       Code reusability
  •       Template
  •       Loose coupling
  •       Abstraction
  •       Dynamic resolution

 There are five important rules you must follow when using abstract classes in Java. These are listed below-

  1.     The keyword “abstract” must be used mandatorily when declaring an abstract class in Java.
  2.     Abstract class cannot directly get instantiated.
  3.     Abstract class needs to have at least one method that is abstract. An abstract class always contains final methods.
  4.     Such classes might also comprise non-abstract methods.
  5. Abstract class might comprise constructors as well as static methods.

A few properties of the abstract classes are:

  • Abstract methods may or may not be present in the Java abstract class.
  • The presence of at least one abstract method in a class makes the class an abstract class.
  • An abstract class cannot have any objects and therefore cannot be directly instantiated.
  • An abstract class can be used only if it is inherited from another class and implements the abstract methods.
  • Proper implementations of the abstract methods are required while inheriting an abstract class.
  • Both regular and abstract methods can be present in a Java abstract class.
  • Parameterized constructors may be present in an abstract class. Also, an abstract class always contains a default constructor.

In-Demand Software Development Skills

Why We Need an Abstract Class in Java 

Abstract classes are a cornerstone of Java’s object-oriented capabilities, providing a mechanism for abstraction and polymorphism. They are essential for defining templates encapsulating the shared structure and behavior, guiding the development of cohesive, flexible, and maintainable codebases. By mandating the implementation of abstract methods in subclasses, abstract classes ensure uniformity and predictability in the application’s architecture. 

The above sequence diagram vividly illustrates the practical application of abstract classes: 

  • Attempt to Execute Abstract Method: The Client initiates a call to AbstractClass to invoke callsAbstractMethod(). Since AbstractClass only declares but does not implement the Method, this action cannot be completed, simulating a real-world scenario where an incomplete class framework prompts a runtime error or a compile-time notification. This behavior enforces the OOP principle that an abstract class is not to be instantiated or utilized directly but serves as a template. 
  • Successful Method Overriding: The Client then interacts with SubClass1, a concrete implementation of AbstractClass. Here, SubClass1 overrides the abstract Method, providing its specific functionality. This successful invocation represents the concept of Method overriding, a form of polymorphism where a subclass provides a specific implementation of a method that is declared in its parent class. 
  • Polymorphic Behavior Across Subclasses: Moving forward, the Client engages with SubClass2, showcasing a variant implementation of the same abstract Method. The distinct response from SubClass2 highlights the versatility of abstract classes — while they ensure a unified interface, they allow for varied behaviors across different subclasses. This aspect is crucial for designing systems that require objects with shared interfaces but diverse functional behaviors. 

In the broader context of software engineering, the need for an abstract class arises from the necessity to define a contract that various implementers can agree upon. Abstract classes facilitate this by allowing developers to dictate a set of actions (methods) that all subclasses must implement, thereby providing a reliable and predictable framework to build upon. 

Rules for Using Abstract Class in Java 

Abstract classes in Java are pivotal in achieving abstraction, a core principle of object-oriented programming. They allow developers to define templates for a group of related classes and enforce a contract that must be followed by any concrete subclass. Understanding and adhering to the rules for using abstract classes is crucial for leveraging their full potential while maintaining code integrity and design clarity. 

To ensure abstract classes are utilized effectively and correctly within your Java applications, here are the essential rules to follow: 

  • Abstract Class Instantiation: It’s important to remember that abstract classes cannot be instantiated directly. They are designed to be subclassed, meaning you can only create instances of non-abstract subclasses that extend these abstract classes. 
  • Abstract and Concrete Methods: An abstract class can have abstract and concrete methods. Abstract methods are declared without an implementation and must be implemented by subclasses, providing a blueprint for the methods that need to be supported. Concrete methods in an abstract class can have a full implementation and can be inherited as is by subclasses. 
  • Abstract Method Declaration: If a class includes even one abstract Method, the class itself must be declared abstract. This rule ensures that the class cannot be instantiated directly and must be extended by a subclass to provide the necessary method implementations. 
  • Constructor Presence: Abstract classes can have constructors. While you cannot instantiate an abstract class directly, constructors can be used by subclasses to perform initialization tasks when a subclass object is created. 
  • Visibility: The visibility rules that apply to classes and methods in Java also apply to abstract classes. Abstract classes and methods can be public, protected, or default, controlling how and where they can be accessed from other classes. 

Abstract methods

Abstract methods are those types of methods that don’t require implementation for its declaration. These methods don’t have a body which means no implementation. A few properties of an abstract method are:

  • An abstract method in Java is declared through the keyword “abstract”.
  • While the declaration of the abstract method, the abstract keyword has to be placed before the name of the method.
  • There is no body in an abstract method, only the signature of the method is present. 
  • An abstract method in Java doesn’t have curly braces, but the end of the method will have a semicolon (;)

abstract double Method(double n1, double n2);

  • Any class that contains an abstract method should be declared as an abstract class. Although the opposite might not be true i.e. it is not necessary that an abstract class should have an abstract method.
  • Inheritance of an abstract class by a regular class requires the implementation of all the abstract methods in the parent class.

Our learners also read: Free java course!

Example of an abstract method

public abstract class Car

{

    private String model;

  private String color;

    private int year;

    public abstract double computePrice();

}

If derived classes don’t implement the abstract methods, it would result in abstract classes that cannot be instantiated. 

A few cannot be used with the abstract keyword in Java.

  • final
  • abstract native
  • abstract static
  • abstract private
  • abstract synchronized
  • abstract strictfp

A code showing the use of an abstract method in Java is shown below. 

Source

The output of the code is:

Java Interfaces

Other than the abstract classes and abstract methods, Java uses interfaces to achieve abstraction. When related methods are grouped together into empty bodies, then it is called an interface. The interface is similar to an abstract class as it is the grouping of abstract methods. When a class implements the interface, all the abstract methods within the interface are inherited. The interface might also contain default methods, constants, and static methods. The method bodies of only the default and the static methods are present. An inheritance and a class can be written in a similar way but a class can describe an object’s attributes and behaviour. While in the case of an interface only those behaviours of an object are present, those are implemented by the class.

A class has to define all the methods of the interface that it implements. Only for an abstract class, the methods are not required to be defined by the class.

An interface is similar to a Java abstract class in the following ways:

  • Any number of methods can be contained in an interface.
  • .java extension is used for writing an interface in a file. The name of the file should match the name of the interface.
  • The .class file contains the byte code of an interface.
  • Interfaces appear in packages. The bytecode file of an interface is present in a directory with the same name as the package name.

An interface is different from a Java abstract class in the following ways:

  • The interface cannot be instantiated.
  • There are no constructors in an interface.
  • The interface contains only abstract methods.
  • No instance fields are present in an interface. A field has to be declared both as static and final if it has to appear in an interface.
  •  Only a class can implement an interface, but cannot be extended.
  • An interface can extend multiple interfaces.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Properties of an Interface

  • There is no need for declaring an interface as abstract through the abstract keyword as it is implicitly abstract.
  • Abstract keywords are not required to declare the methods as abstract as they are implicitly abstract.
  • All the methods in an interface are implicitly public.

How to declare an interface?

The keyword “interface” is used to declare an interface. Total abstraction is provided through the use of an interface. By default, all the methods within an interface are abstract and public. This means there is nobody of the methods in an interface and all the fields are static, public, and final. 

Syntax of an interface: 

Interface name_of_the_interface {

# declare fields

# declare abstract methods

}

For example interface Player

{
     final int age = 40;

     int calc();

}

Learn Java Tutorials

How to implement an interface?

To implement an interface the keyword ‘implements’ is used. More than one interface can be implemented by a class. In such cases, the keyword ‘implements’ is followed by a list of interfaces separated by a comma. The keyword is used in the class declaration.

An Example of implementing the interface is shown below:

class Maruti implements Car

An example of a code showing the implementation of an interface in Java is shown below.

Source

The code generates the following output:

A code applying the implementation of multiple interfaces is shown below. 

Source 

The code generates the following output:

Some text…

Some other text…

Why interface is used?

  • Interfaces are used for achieving total abstraction.
  • Multiple inheritances in Java can be achieved through the use of inheritance as Java does not support multiple inheritances.
  • Loose coupling can be achieved through the use of an interface.
  • Through the use of implementation abstraction in java can be achieved.

Although abstraction in Java can be achieved through Java abstract class, interfaces are used as they contain final, public and static variables. However, non-final variables may be present in an abstract class.

If both the Java interface and Java abstract class are used to achieve abstraction, when should an interface and abstract class be used?

  • An abstract class is used when the user needs to define a template for a group of subclasses.
  • An interface is used when a user needs to define a role for other classes.
Ads of upGrad blog

A few advantages of abstraction are:

  • The complexity of the program is reduced.
  • There are lesser chances of code duplication increasing the reusability.
  • The security of a program is increased through the use of abstraction as only a few details are provided to the user.

Read our Popular Articles related to Software Development

Conclusion

This article explores the abstract class in Java and methods, focusing on simplifying code by hiding unnecessary details. Java achieves this through abstract classes and interfaces, with interfaces offering full abstraction and abstract classes providing partial abstraction. As a professional, I’ve learned the importance of knowing when to use each. Interfaces are ideal for complete hiding, while abstract classes offer flexibility. My experience has shown that understanding these differences and similarities is crucial to avoiding errors in code. Mastering these concepts is essential for enhancing the quality and efficiency of our work.  

Suppose you are interested in learning more and implementing the concepts in real-life problems. In that case, I suggest you check out the Masters in Computer Science course provided by upGrad and IIIT-Bangalore, recognized by Liverpool John Moores University. The course is designed for entry-level professionals (21-45 years of age), providing 500+ hours of training from leading industry experts and software engineering faculties. Further details of the course can be checked at upGrad’s official webpage

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is Java?

Java is an object-oriented programming language, which implies that all programmes are made up of entities that represent concepts or physical objects, which are referred to as objects. Desktops, servers, portable devices, smart cards, and discs all include Java programmes. It creates software for a variety of platforms. When a programmer creates a Java application, the compiled code, also known as bytecode, is generated. They are compatible with a wide range of operating systems (OS), including Windows, Linux, and Mac OS. Java requires simply the installation of the Java Runtime Environment (JRE) to function, independent of the instrument used.

2What is a Class in Java?

In Java, a class is a logical template for creating objects who have the same characteristics. Objects are the units or the group of things which together form the classes. The essential class attributes should be present in all class objects. The actual attributes or values, as well as any methods that the object may utilize, are considered core properties. There are several elements to a class declaration. Modifiers, Class name, Superclass (if available), Implemented Interfaces, Appropriate Keywords (depending on if the class expands from a Superclass or handles one or more interfaces), and Class body within curly brackets are all included.

3Where do we use interfaces in Java?

In Java, an interface is a list of method prototypes. Users can design an interface if they need to direct the programmer or construct a contract stating how the methods and fields of a type should be. Users must implement this interface, supply the body for all of the interface's abstract methods, and retrieve the object of the implementing class to create an object of this kind. The interface's goal is to facilitate communication while also introducing multiple inheritance. Communication is one of the functions of the interface. Users can describe how they want a type's methods and fields to work through the interface. Multiple inheritance is not supported by Java; nevertheless, users can accomplish multiple inheritance by utilizing interfaces.

4What is Java?

5What is a Class in Java?

In Java, a class is a logical template for creating objects who have the same characteristics. Objects are the units or the group of things which together form the classes. The essential class attributes should be present in all class objects. The actual attributes or values, as well as any methods that the object may utilize, are considered core properties. There are several elements to a class declaration. Modifiers, Class name, Superclass (if available), Implemented Interfaces, Appropriate Keywords (depending on if the class expands from a Superclass or handles one or more interfaces), and Class body within curly brackets are all included.

6Where do we use interfaces in Java?

In Java, an interface is a list of method prototypes. Users can design an interface if they need to direct the programmer or construct a contract stating how the methods and fields of a type should be. Users must implement this interface, supply the body for all of the interface's abstract methods, and retrieve the object of the implementing class to create an object of this kind. The interface's goal is to facilitate communication while also introducing multiple inheritance. Communication is one of the functions of the interface. Users can describe how they want a type's methods and fields to work through the interface. Multiple inheritance is not supported by Java; nevertheless, users can accomplish multiple inheritance by utilizing interfaces.