Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconWhat is Adapter Class in Java? Advantages of Adapter Class and its Types

What is Adapter Class in Java? Advantages of Adapter Class and its Types

Last updated:
19th May, 2021
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
What is Adapter Class in Java? Advantages of Adapter Class and its Types

What Is An Adapter-Class?

In JAVA, an adapter class allows the default implementation of listener interfaces. The notion of listener interfaces stems from the Delegation Event Model. It is one of the many techniques used to handle events in Graphical User Interface (GUI) programming languages, such as JAVA.

GUI programming is predominantly event-driven, with the user interacting with the system through associated visuals and graphics. This means that every activity initiated by the user, such as a mouse’s movement that changes the mouse pointer’s coordinates on the screen, clicks a button or scrolling a page, is considered an independent event. 

Check out our free courses to get an edge over the competition.

Explore Our Software Development Free Courses

Each of these independent event activities is intrinsically linked to a code segment that iterates what response the application should provide to the user. The pathway is simple. The user (source) generates an event and sends it to one or more listener interfaces. Once an event potential is received, the listener interface processes the event and returns the suitable response.

Ads of upGrad blog

This pathway substantiates the process of event handling. An adapter class in JAVA is therefore used to implement an interface having a set of dummy methods. If a programmer chooses to inherit an adapter class, they will not be forced to implement all the methods listed under a particular listener interface. The adapter class can further be subclassed so that the programmer can override only required methods. In other words, by using an adapter class, the programmer can rapidly construct their own listener interface to field events. This helps save code. 

Check out upGrad’s Java Bootcamp

What Is The Relationship Between An Adapter Class and a Listener Interface?

Listeners are used when the programmer intends to utilize most of the methods listed under the interface. If a listener interface is implemented directly by a class, all the methods within that interface need to be implemented, making the code unreasonably large. This complexity can be resolved by calling upon an adapter class. An adapter class proves essential in instances where an event calls for only specific methods.

The programmer has only to create a subclass of it and override the interest methods to use an adapter class. Adapter classes are, therefore, beneficial for listener interfaces in JAVA having more than one method. To better understand this, let us consider the example of the MouseListener interface. This interface is notified whenever there is a change in the state of the mouse. It has five methods, mouse clicked, mouseExited, mouseEntered, mousePressed, and mouseReleased.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

When notified against an event, even if only of these methods is necessary, all of them need to be implemented. The methods that are not needed are kept empty. An adapter class is used to avoid this unnecessary implementation of an empty method body. 

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Understanding The Adapter Design Pattern

In non-technical parlance, an adapter, by definition, is structurally designed to allow two incompatible interfaces to work together. An adapter pattern is therefore capable of making two incompatible interfaces compatible without changing their existing code. The corresponding interfaces may be inconsistent, but their inner functionalities should match the requirement being sought. To better clarify this, let us consider a relevant example. 

We are aware that different countries have different electric sockets, voltages, and frequency measurements. If we have to make use of an appliance designed per one country’s specification in another, we need to make sure the appliance is compatible.

For instance, in the UK, type G sockets are commonly used, in the US and Japan, type A and type B sockets, and in India, type C, type D, and type M. A laptop or mobile device carried from India will therefore be incompatible with the electric specifications of say, US and Japan. This is where an adapter’s purpose becomes essential for converting an incompatible code into a compatible code. 

Types of Adapter Classes

Adapter classes can be found in java. awt.the event, java.awt.dnd and java.swing.event packages. The standard adapter classes with their corresponding listener interfaces in JAVA are mentioned below for each of these packages. 

 1. java. awt. eve

Adapter ClassListener Interface
WindowAdapterWindowListener
KeyAdapterKeyListener
MouseAdapterMouseListener
MouseMotionAdapterMouseMotionListener
FocusAdapterFocusListener
ComponentAdapterComponentListener
ContainerAdapterContainerListener
HierarchyBoundsAdapterHierarchyBoundsListener

 2. java.awt.dnd

Adapter ClassListener Interface
DragSourceAdapterDragSourceListener
DragTargetAdapterDragTargetListener

3. javax.swing.event

Adapter ClassListener Interface
MouseInputAdapterMouseInputListener
InternalFrameAdapterInternalFrameListener

These are present in the Abstract Window Toolkit of their respective Java packages. To understand the nature of methods contained within listener interfaces, let us consider a few examples:

  1. The WindowListener interface defines methods related to window events, including opening and closing of a window, activation and deactivation of a window, and the iconification and detoxification of a window.
  2. The KeyListener interface defines methods that handle key events that are fired by the user interacting with keyboard components. 
  3. The MouseListener interface is notified when a mouse is stable and receives event potential related to exiting, entering, clicking, pressing, or releasing component on the user’s visual frame. 
  4. The Component Listener interface receives component event potentials. Here, a component refers to any graphical object designed to interact with the user, such as buttons, checkboxes, and scroll bars. 

In-Demand Software Development Skills

Difference Between Class Adapter and Object Adapter

To guarantee functionality and flexibility, object-oriented programming such as JAVA offers programmers features such as inheritance and composition. If you try to reuse a particular code by inheriting its features from another class, the subclass you create will remain dependent on the parent class throughout the entire program’s length.

This makes the system, in many cases, increasingly complex and less testable and makes the exchange of functionality at run-time painstakingly hard. In composition, one class only uses another. Decoupling between the two is further promoted by clearly defining the interfaces.

Ads of upGrad blog

The debate between class adapter versus object adapter can therefore be resolved as follows. Class Adapter uses inheritance and is therefore capable of only wrapping a class. It cannot wrap an interface because, by definition, it must derive from some base class. An object adapter uses composition and is therefore capable of wrapping both classes and interfaces. This is primarily achieved because, in composition, each class or interface is a private, encapsulated member. 

Advantages of an Adapter Class

  1. An adapter class assists unrelated classes in working together.
  2. With the use of an adapter class, the same class can be used in multiple ways. 
  3. Users are provided with the option of a pluggable kit for developing applications. Class usage, therefore, becomes highly reusable. 
  4. It enhances the transparency of classes. 
  5. It provides a way to include related patterns in a class. 

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

Read our Popular Articles related to Software Development

Conclusion

With this article, we have understood the mechanics of an adapter class in JAVA, the three main packages that contain adapter classes, and the benefits of adapter classes to programmers. Adapter classes are abstract classes for receiving various events and exist as a convenience for creating listener objects. With their different functionalities, adapter classes offer programmers the platform to be innovative via Swing methodology.

If you wish to improve your Java skills, you need to get your hands on these java projects. If you’re interested to learn more about Java, full-stack development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development, which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

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 adapter class in Java?

Adapter class is a class that is defined using the adapter pattern. An adapter can be used to add new capabilities to an existing class without modifying the original class. For example, the java.util.Scanner class is from java.util package. The Scanner class cannot read from a file as a file is not an InputStream. To read from a file we create an adapter class that accepts an InputStream as an argument and returns the processed data as an object. Adapter pattern is used to extend the functionality of an existing class without modifying its code in any way.

2What are design patterns in Java?

A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. In object-oriented programming, design patterns are established conventions that ease the design and implementation of software systems. There are several design patterns in Java. It is not necessary that a design pattern has to be taken from another language. Design patterns can be written in a very simple and short form.

3Which is the most used design pattern in Java?

You will find many design patterns in java. The single most used design pattern is Factory Pattern. It has many applications in enterprise development. It helps in removing dependency on concrete classes in the application. Let us give you a real-life example. In an e-commerce application, you might have a requirement to create an object of a user in both test and production environment. The user class may have many subclasses like Admin, Shopkeeper, Seller, User etc. The common main method in factory pattern looks like: public class UserFactory { public static Object create () { User user = createAdmin (); // see if admin is allowed return user ; // return current user } }. See here how the user class is not dependent on concrete class. Although it's not a complete example, it shows you how the Factory pattern works.

Explore Free Courses

Suggested Blogs

Top 40 MySQL Interview Questions & Answers For Beginners & Experienced [2023]
117546
Have a Data engineering or data science interview coming up? Need to practice some of the most asked MySQL interview questions? The article compiles t
Read More

by Rohan Vats

07 Nov 2023

Literals In Java: Types of Literals in Java [With Examples]
5839
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

29 Oct 2023

10 Interesting HTML Project Ideas & Topics For Beginners [2023]
392076
Summary In this article, you will learn 10 Interesting HTML Project Topics. Take a glimpse below. A tribute page A survey form Technical documentati
Read More

by Rohan Vats

04 Oct 2023

15 Exciting SQL Project Ideas & Topics For Beginners [2023]
284531
Summary: In this Article, you will learn 15 exciting SQL project ideas & topics for beginners. Library Management System Centralized College Dat
Read More

by Rohan Vats

24 Sep 2023

17 Interesting Java Project Ideas & Topics For Beginners 2023 [Latest]
34083
Summary: In this article, you will learn the 17 Interesting Java Project Ideas & Topics. Take a glimpse below. Airline reservation system Data v
Read More

by Rohan Vats

24 Sep 2023

9 Exciting Software Testing Projects & Topics For Beginners [2023]
8132
Software testing might constitute 50% of a software development budget but it is viewed as a lethargic and unnecessary step by most students. Even edu
Read More

by Rohan Vats

21 Sep 2023

Top 10 Skills to Become a Full-Stack Developer in 2023
217999
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

21 Sep 2023

Java Free Online Course with Certification [2023]
56825
The PYPL Popularity of Programming Language Index maintains that Java is the second most popular programming language in the world, after Python.  Alt
Read More

by Rohan Vats

20 Sep 2023

Salesforce Developer Salary in India in 2023 [For Freshers & Experienced]
903110
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

20 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon