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:

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

Main.java
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.

BankSystem.java
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

Main.java
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.

SmartPhone.java
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

Step-by-Step Process

  1. Define the interface.
  2. Write the implementing classes.
  3. In main(), use interface references to control the objects.

Expected Deliverables

Solve in Compiler