Java Lab Handout 4 – Abstraction
Objective:
To understand and implement the concept of Abstraction in Java using real-life examples (MB – our
photocopy & handouts provider).
Theory Recap:
Abstraction is the process of hiding internal implementation details and showing only essential
features.
In Java, abstraction can be achieved using:
1. Abstract classes
2. Interfaces
Key Point: Users interact only with the services (what it does), not with the implementation (how it
does it).
Real-Life Example (MB & Handouts):
MB provides two services:
- Black & White Printing
- Color Printing
Teachers give their labs to MB, and students simply ask: “MB, please give me Sir Mir’s Lab 4
(Java).”
Students don’t worry about how MB’s printer works internally — they just get the result.
This is abstraction in action!
Lab Task 1 – Abstract Class Example
// Abstract Class
abstract class PhotocopyService {
abstract void printBlackAndWhite(String labName);
abstract void printColor(String labName);
void welcomeMessage() {
System.out.println("Welcome to MB's Photocopy Machine!");
}
}
class MB extends PhotocopyService {
@Override
void printBlackAndWhite(String labName) {
System.out.println("Printing Black & White copy of " + labName);
}
@Override
void printColor(String labName) {
System.out.println("Printing Color copy of " + labName);
}
}
public class Lab4Task1 {
public static void main(String[] args) {
PhotocopyService service = new MB();
service.welcomeMessage();
service.printBlackAndWhite("Java Lab 4");
service.printColor("Java Lab 4");
}
}
Lab Task 2 – Interface Example
// Interface
interface HandoutProvider {
void giveLabHandout(String teacherName, String labName);
}
class MBHandouts implements HandoutProvider {
@Override
public void giveLabHandout(String teacherName, String labName) {
System.out.println("MB gives " + labName + " of " + teacherName + " to the student.");
}
}
public class Lab4Task2 {
public static void main(String[] args) {
HandoutProvider provider = new MBHandouts();
provider.giveLabHandout("Sir Mir", "Java Lab 4");
provider.giveLabHandout("Sir Shahjhan", "ICT Lab 2");
}
}
Student Tasks (To Do in Lab):
1. Modify the program so MB can also provide Notes in addition to Lab Handouts.
2. Add another class PhotocopyAssistant (helper) who can also provide prints when MB is busy.
3. Create a scenario where three teachers (use real names: Sir Mir, Sir Shahjhan) send their labs,
and students request them.
Output Example:
Welcome to MB's Photocopy Machine!
Printing Black & White copy of Java Lab 4
Printing Color copy of Java Lab 4
MB gives Java Lab 4 of Sir Mir to the student.
MB gives ICT 2 of Sir Shahjhan to the student.