Chapter 7 — Abstraction & Interfaces
📚 Chapter Overview
Abstraction is the process of hiding the implementation details and showing only the functionality to the user. In this chapter, you will learn how to use Abstract Classes and Interfaces to define "Contracts" for your code.
Learning Objectives:
- Understand the
abstractkeyword for classes and methods. - Master multiple inheritance using
Interfaces. - Compare Abstract Classes vs Interfaces.
7.1 Abstract Classes
Part 1 — Definition
An Abstract Class is a restricted class that cannot be used to create objects. To access it, it must be inherited from another class. It can have both abstract methods (without a body) and regular methods (with a body).
Part 2 — Syntax
abstract class Animal {
abstract void makeSound(); // No body
void sleep() { System.out.println("Zzz"); }
}
Part 3 — Example
Problem: Create an abstract Bank class with a method to get interest rate.
abstract class Bank {
abstract int getInterest();
}
class SBI extends Bank {
int getInterest() { return 7; }
}
Part 4 — Video
Video: Coming Soon
7.2 Interfaces
Part 1 — Definition
An Interface is a completely "abstract class" that is used to group related methods with empty bodies. Interfaces are used to achieve abstraction and multiple inheritance in Java. A class implements an interface.
Part 2 — Syntax
interface Drawable {
void draw(); // Implicitly public and abstract
}
class Circle implements Drawable {
public void draw() { ... }
}
Part 3 — Example
Problem: Model a smartphone that acts as both a Camera and a Phone.
interface Camera { void takePhoto(); }
interface Phone { void call(); }
class SmartPhone implements Camera, Phone {
public void takePhoto() { System.out.println("Click!"); }
public void call() { System.out.println("Calling..."); }
}
Observation: A class can implement multiple interfaces, but can only extend one class.
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Remote Control" system for various Electronic Devices.
Requirements
- Create an interface
RemoteControlwithpowerOn()andpowerOff(). - Implement the interface in
TVandAirConditionerclasses. - Ensure each class prints a unique message (e.g., "TV is starting", "AC cooling...").
Step-by-Step Process
- Define the interface.
- Write the implementing classes.
- In
main(), use interface references to control the objects.
Expected Deliverables
InterfaceChallenge.javasource code.