Convert the interface of a class into another interface the clients expect
Java Examples:
Stream classes
InputStreamReader converts InputStream to Reader interface
Arrays.asList()
Convert (Wraps) array to List interface
ArrayList class behaves as adapter of array to List interface
The adapter class implements output type interface and behaves like the interface
Implementation
interface Student { public String getName(); public String getSurName();}class CollegeStudent implements Student { private String name; private String surName; @Override public String getName() { return this.name; } @Override public String getSurName() { return this.surName; }}class SchoolStudent { private String firstName; private String lastName; public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; }}// Create an Adapter of type Studentclass SchoolStudentAdapter implements Student { private SchoolStudent schoolStudent; public SchoolStudentAdapter(SchoolStudent student) { this.schoolStudent = schoolStudent; } @Override public String getName() { return this.schoolStudent.getFirstName(); } @Override public String getSurName() { return this.schoolStudent.getLastName(); }}
Driver
public class Demo { public static void main(String[] args) { SchoolStudent schoolStudent = new SchoolStudent("Rohan", "Roy"); // convert "SchoolStudent" to "Student" type Student s = new SchoolAdapter(schoolStudent) }}