Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Abstract Class in Java and Methods [With Examples]

Updated on 21 October, 2024

79.1K+ views
17 min read

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

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.

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.

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

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();

}

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

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.

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.

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.

Frequently Asked Questions (FAQs)

1. What 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.

2. What 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.

3. Where 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.

4. What 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.

5. Where 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.

RELATED PROGRAMS