Java Tutorial chapters (15)
  1. 01Java Introduction
  2. 02Java Variables & Data Types
  3. 03Java Control Statements
  4. 04Java OOPs Basics
  5. 05Java Inheritance & Polymorphism
  6. 06Java Abstraction & Interfaces
  7. 07Java Strings
  8. 08Java Arrays
  9. 09Java Exception Handling
  10. 10Java Collections Framework
  11. 11Java Multithreading
  12. 12Java 8 Features
  13. 13Java I/O & File Handling
  14. 14Java JDBC
  15. 15Java MCQ

Chapter 06

Java Abstraction & Interfaces

6 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Abstraction hides implementation details and shows only essential features.

In Java it is achieved with abstract classes and interfaces.

This chapter also covers encapsulation, packages and access modifiers, which together control how code is organised and protected.

Large systems depend on contracts (interfaces), hidden data (encapsulation) and organised code (packages).

These topics are asked in almost every Java interview.

Database drivers (JDBC interfaces), Spring services, plug-in architectures, API design and library packaging.

1

Abstract Class in Java

An abstract class is a class declared with the abstract keyword that cannot be instantiated. It may contain abstract methods (without body) and concrete methods (with body), fields and constructors. A subclass must implement all abstract methods or be abstract itself.

In short: An abstract class is an unfinished blueprint. Children must complete the missing parts.

Think about it

It shares common code among related classes while forcing each child to supply its own special behaviour. An abstract Report class with generate() as a template; PdfReport and CsvReport implement the format step.

An abstract method has no body and ends with a semicolon: abstract double area();.

If a class has even one abstract method, the class must be declared abstract.

You cannot create an object with new AbstractClass(), but you can use it as a reference type.

An abstract class can have constructors (called through super() from child constructors), instance and static fields, final methods, static methods and any access level.

abstract cannot be combined with final (a final class cannot be extended), private (it could not be overridden) or static.

An abstract class can be abstract without having any abstract method, just to stop instantiation.

Use the template method pattern: the abstract class defines the algorithm in a final method and leaves some steps abstract.

Key points

  • abstract method: Method declaration without a body.
  • concrete method: Normal method with a body.
  • Template method: Fixed algorithm with customisable steps.
  • Instantiate: Create an object with new.
  • Abstract classes cannot be instantiated.
  • abstract + final or abstract + private is illegal.
  • An abstract class can have constructors and fields.
  • A child that does not implement all abstract methods must itself be abstract.

Example

Code
abstract Bank with template method:
abstract class Bank {
    protected String name;

    Bank(String name) { this.name = name; }        // constructors are allowed

    abstract double interestRate();                // no body

    final void printInfo() {                       // template method
        System.out.println(name + " gives " + interestRate() + "% interest");
    }

    void welcome() {                               // concrete method
        System.out.println("Welcome to " + name);
    }
}

class Sbi extends Bank {
    Sbi() { super("SBI"); }
    @Override double interestRate() { return 6.8; }
}

class Icici extends Bank {
    Icici() { super("ICICI"); }
    @Override double interestRate() { return 7.2; }
}

public class AbstractDemo {
    public static void main(String[] args) {
        // Bank b = new Bank("X");     // error: Bank is abstract; cannot be instantiated
        Bank[] banks = { new Sbi(), new Icici() };
        for (Bank b : banks) {
            b.welcome();
            b.printInfo();
        }

        Bank anon = new Bank("LocalBank") {         // anonymous subclass
            @Override double interestRate() { return 5.0; }
        };
        anon.printInfo();
    }
}
2

Interface in Java

An interface is a reference type that defines a contract: a set of method signatures (and constants) that implementing classes must provide. A class implements an interface with the implements keyword. Interfaces achieve full abstraction and multiple inheritance of type.

In short: An interface is a promise: any class that implements it promises to provide these methods.

Contract vs partial implementation

Think about it

Interfaces separate what a class does from how it does it, enabling loose coupling and easy testing. JDBC Connection, List, Comparable and Runnable are all interfaces; your code depends on them, not on one implementation.

Members: fields are implicitly public static final; methods are implicitly public abstract.

Since Java 8 an interface can have default methods (with body, inherited by implementers) and static methods; since Java 9 it can have private methods that share code between default methods.

A class can implement many interfaces: class C implements A, B. An interface can extend several interfaces: interface C extends A, B. An interface cannot have constructors or instance fields and cannot be instantiated, but you can create an anonymous class or a lambda for a functional interface (one abstract method, marked with @FunctionalInterface).

If two interfaces give the same default method, the class must override it and can choose with A.super.

hello().

A marker interface has no methods (Serializable).

Implementing methods must be public because interface methods are public.

Since Java 17 sealed interfaces limit which classes may implement them.

Key points

Example

Code
default, static and private methods:
interface Drawable {
    int MAX_SIZE = 100;                       // public static final
    void draw();                              // public abstract

    default void describe() {                 // default method (Java 8)
        System.out.println("Drawing a shape, max size " + MAX_SIZE);
        log("describe");
    }

    static Drawable of(String name) {         // static method
        return () -> System.out.println("Drawing " + name);
    }

    private void log(String msg) {            // private method (Java 9)
        System.out.println("[log] " + msg);
    }
}

interface Resizable {
    void resize(int percent);
}

class Circle implements Drawable, Resizable { // multiple interfaces
    int radius = 10;
    public void draw() { System.out.println("Circle radius " + radius); }
    public void resize(int percent) { radius = radius * percent / 100; }
}

interface Walker { default String move() { return "walk"; } }
interface Swimmer { default String move() { return "swim"; } }

class Duck implements Walker, Swimmer {
    @Override
    public String move() {                    // must resolve the conflict
        return Walker.super.move() + " and " + Swimmer.super.move();
    }
}

public class InterfaceDemo {
    public static void main(String[] args) {
        Circle c = new Circle();
        c.draw();
        c.resize(150);
        c.draw();                             // radius 15
        c.describe();

        Drawable d = Drawable.of("Square");   // lambda as interface implementation
        d.draw();

        System.out.println(new Duck().move()); // walk and swim
        System.out.println(Drawable.MAX_SIZE);
    }
}
3

Abstract Class vs Interface

An abstract class is a partially implemented class that can hold state and constructors and is extended by one parent. An interface is a contract of behaviour with no instance state, which a class can implement in multiples.

In short: Use an abstract class when classes share code and state. Use an interface when unrelated classes share only behaviour.

Think about it

Choosing wrongly leads to rigid code or duplicated code, and this is one of the most asked interview questions. List is an interface, AbstractList is a skeletal abstract class and ArrayList is the concrete class.

Differences: 1) Keyword: extends for abstract class, implements for interface.

2) Inheritance: a class extends only one abstract class but implements many interfaces.

3) Methods: abstract class may have abstract and concrete methods with any access; interface methods are public (abstract, default, static, private).

4) Variables: abstract class may have instance variables of any kind; interface has only public static final constants.

5) Constructors: allowed in abstract class, not in interface.

6) Purpose: abstract class models IS-A with shared implementation (partial abstraction); interface models CAN-DO capability (100% contract abstraction, with default methods as an extension).

7) Speed and evolution: adding an abstract method to an abstract class or interface breaks children, but a default method added to an interface does not.

Guideline: start with an interface; add an abstract skeletal class (like AbstractList) when you want shared code.

Key points

Example

Code
when to use each:
// Interface = capability, abstract class = shared base
interface Flyable { void fly(); }
interface Swimmable { void swim(); }

abstract class Animal {
    protected String name;                       // state
    Animal(String name) { this.name = name; }    // constructor
    void sleep() { System.out.println(name + " sleeps"); }   // shared code
    abstract void sound();                       // must be implemented
}

class Duck extends Animal implements Flyable, Swimmable {
    Duck() { super("Duck"); }
    void sound() { System.out.println("Quack"); }
    public void fly() { System.out.println(name + " flies"); }
    public void swim() { System.out.println(name + " swims"); }
}

class Fish extends Animal implements Swimmable {
    Fish() { super("Fish"); }
    void sound() { System.out.println("..."); }
    public void swim() { System.out.println(name + " swims"); }
}

public class AbstractVsInterface {
    public static void main(String[] args) {
        Duck d = new Duck();
        d.sleep();
        d.sound();
        d.fly();
        Swimmable[] swimmers = { d, new Fish() };    // unrelated types share one capability
        for (Swimmable s : swimmers) s.swim();
    }
}
/*
Feature           Abstract class              Interface
Keyword           extends                     implements
Multiple          one parent only             many interfaces
Fields            any kind                    public static final only
Constructors      yes                         no
Methods           abstract + concrete         abstract, default, static, private
*/
4

Encapsulation in Java

Encapsulation is the OOP principle of binding data (fields) and the methods that work on it into a single class, and restricting direct access to the data by making fields private and exposing them through public getter and setter methods.

In short: Keep the data inside a capsule and let outsiders use only safe doors.

Think about it

Without it any code can set an age to -5 or a balance to a wrong value and bugs spread everywhere. A BankAccount that allows deposits and withdrawals only through validated methods, never by changing balance directly.

To fully encapsulate a class: 1) declare fields private; 2) provide public getters (read) and setters (write) only where needed; 3) validate input inside setters so the object never becomes invalid.

Benefits

control over data, flexibility to change internals without breaking users, easier testing and security.

A read-only class has only getters; a write-only class has only setters.

An immutable class goes further: the class is final, all fields are private final, no setters, values are set only in the constructor, and mutable inputs are defensively copied.

Java records (Java 16+) create immutable data carriers with one line.

Encapsulation is not the same as abstraction: encapsulation hides data; abstraction hides implementation complexity.

Key points

  • Getter: Method that returns a field value.
  • Setter: Method that sets a field value, usually with validation.
  • Data hiding: Making fields private.
  • Immutable class: Class whose objects never change after creation.
  • Defensive copy: Copying a mutable argument or result to protect internal state.
  • Fields private, methods public is the standard pattern.
  • Validation belongs inside setters or business methods.
  • A class with only getters is read-only.
  • Encapsulation = data hiding; abstraction = implementation hiding.

Example

Code
Account and immutable Team:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Account {
    private final String id;
    private double balance;

    Account(String id, double opening) {
        this.id = id;
        setBalanceInternal(opening);
    }

    private void setBalanceInternal(double b) {
        if (b < 0) throw new IllegalArgumentException("Negative balance");
        balance = b;
    }

    public String getId() { return id; }
    public double getBalance() { return balance; }

    public void deposit(double amt) {
        if (amt <= 0) throw new IllegalArgumentException("Invalid amount");
        balance += amt;
    }

    public void withdraw(double amt) {
        if (amt <= 0 || amt > balance) throw new IllegalArgumentException("Cannot withdraw " + amt);
        balance -= amt;
    }
}

final class Team {                           // immutable class
    private final String name;
    private final List<String> members;

    Team(String name, List<String> members) {
        this.name = name;
        this.members = new ArrayList<>(members);        // defensive copy
    }
    String getName() { return name; }
    List<String> getMembers() { return Collections.unmodifiableList(members); }
}

public class EncapsulationDemo {
    public static void main(String[] args) {
        Account a = new Account("A101", 1000);
        a.deposit(500);
        a.withdraw(300);
        System.out.println(a.getId() + " balance " + a.getBalance());   // 1200.0
        // a.balance = 99999;                   // error: balance has private access
        try {
            a.withdraw(5000);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        List<String> src = new ArrayList<>(List.of("Asha", "Ravi"));
        Team t = new Team("Alpha", src);
        src.add("Hacker");                       // does not affect the team
        System.out.println(t.getMembers());      // [Asha, Ravi]
    }
}
5

Package in Java

A package is a namespace that groups related classes, interfaces and sub-packages. It avoids name conflicts, controls access and keeps large programs organised. The package statement must be the first statement of a source file.

In short: A package is a folder for related classes. The same class name can exist in two different packages.

Modules plug into your program

Think about it

Packages prevent naming clashes, support access control and keep thousands of classes manageable. com.company.app.controller, com.company.app.service and com.company.app.repository in a typical Spring project.

Types: built-in packages such as java.

lang (imported automatically), java.

util, java.

io, java.

time, java.

sql, and user-defined packages.

Syntax

package com.

shop.

model; The folder structure must match the package name: com/shop/model/Product.

java.

Compile with the -d option to place class files in the right folders: javac -d out com/shop/model/Product.

java.

Run with the fully qualified name: java -cp out com.

shop.

Main.

Importing: import java.

util.

List; imports one class, import java.

util.

*; imports all classes of that package (not sub-packages) and import static java.

lang.

Math.

*; imports static members.

If two classes have the same simple name (java.

util.

Date and java.

sql.

Date) use the fully qualified name for one of them.

Only one package statement is allowed per file and it comes before imports.

Package names are lowercase, usually the reversed domain name.

Packages are the basis of the default access level and of JAR files; Java 9 modules add another layer above packages.

Key points

  • Fully qualified name: Package name plus class name, e.g. java.util.List.
  • import: Makes a class usable by its simple name.
  • classpath: Places where the JVM looks for class files.
  • java.lang: Package imported automatically (String, System, Math).
  • The package statement is the first non-comment line in the file.
  • import java.util.* does not import sub-packages like java.util.function.
  • java.lang is imported by default.
  • Folder structure must match the package name.

Example

Code
three files in packages:
// ---------- File: com/shop/model/Product.java ----------
package com.shop.model;

public class Product {
    private final String name;
    private final double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
    public String getName() { return name; }
    public double getPrice() { return price; }
}

// ---------- File: com/shop/util/PriceUtil.java ----------
package com.shop.util;

public class PriceUtil {
    public static double withTax(double price, double rate) {
        return price + price * rate;
    }
}

// ---------- File: com/shop/Main.java ----------
package com.shop;

import com.shop.model.Product;
import com.shop.util.PriceUtil;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Product> cart = new ArrayList<>();
        cart.add(new Product("Pen", 10));
        cart.add(new Product("Book", 250));

        for (Product p : cart) {
            System.out.println(p.getName() + " -> " + PriceUtil.withTax(p.getPrice(), 0.18));
        }

        java.sql.Date sqlDate = new java.sql.Date(0);   // fully qualified to avoid clash
        java.util.Date utilDate = new java.util.Date(0);
        System.out.println(sqlDate + " " + (utilDate != null));
    }
}

// Compile: javac -d out com/shop/model/Product.java com/shop/util/PriceUtil.java com/shop/Main.java
// Run    : java -cp out com.shop.Main
6

Access Modifiers in Java

Access modifiers control the visibility of classes, fields, methods and constructors. Java has four levels: private, default (package-private, no keyword), protected and public.

In short: They decide who is allowed to see and use a member.

Encapsulation: hide inner details

Think about it

Correct access control protects internal data and defines the public API of a class or library. A library exposes a few public methods and keeps everything else private or package-private.

private: visible only inside the same class.

default (no keyword): visible inside the same package.

protected: visible in the same package and in subclasses of any package (through inheritance).

public: visible everywhere.

Table of access: same class - all four allowed; same package - default, protected, public; subclass in another package - protected (via inheritance) and public; any other class - public only.

For top-level classes only public and default are allowed; private and protected are not.

Members of an interface are public by default.

Constructors can be private (Singleton, utility classes).

A method cannot be overridden with a weaker access level.

Follow the principle of least privilege: start with private and open up only when needed.

The non-access modifiers (static, final, abstract, synchronized, volatile, transient) are different and can be combined with access modifiers.

Key points

  • private: Accessible only within the same class.
  • default: Accessible within the same package (no keyword).
  • protected: Accessible within the package and in subclasses.
  • public: Accessible from everywhere.
  • Least privilege: Give the smallest access that works.
  • A top-level class can only be public or default.
  • protected = package + subclasses.
  • default access has no keyword; do not write the word default for it.
  • Private members are not inherited and cannot be overridden.

Example

Code
four access levels across packages:
// ---------- File: pack1/Base.java ----------
package pack1;

public class Base {
    private int a = 1;          // same class only
    int b = 2;                  // default: same package only
    protected int c = 3;        // same package + subclasses
    public int d = 4;           // everywhere

    public void show() {
        System.out.println(a + " " + b + " " + c + " " + d);   // all visible here
    }
}

// ---------- File: pack1/SamePackage.java ----------
package pack1;

class SamePackage {
    void test() {
        Base x = new Base();
        // System.out.println(x.a);   // error: private
        System.out.println(x.b);      // ok
        System.out.println(x.c);      // ok
        System.out.println(x.d);      // ok
    }
}

// ---------- File: pack2/Child.java ----------
package pack2;

import pack1.Base;

public class Child extends Base {
    void test() {
        // System.out.println(b);     // error: default access
        System.out.println(c);        // ok: protected via inheritance
        System.out.println(d);        // ok: public
        Base other = new Base();
        // System.out.println(other.c); // error: protected not accessible through a Base reference here
        System.out.println(other.d);  // ok
    }

    public static void main(String[] args) {
        new Child().test();
        new Base().show();
    }
}

Solved examples

Example 01 · Basic

Why does Shape s = new Shape(); give a compile error when Shape is abstract?

Given Data:
    Required To Find:

    Reason and fix

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: An abstract class may have unimplemented methods
    Step 2: Creating an object of it would leave behaviour undefined
    Step 3: Create an object of a concrete subclass instead
    Final Answer: Use Shape s = new Circle(5); where Circle extends Shape and implements all abstract methods.

    Approach note: You can still use the abstract class as a reference type.

    Example 02 · Intermediate

    Interfaces A and B both define default String hello(). Class C implements A, B. What must C do?

    Given Data:
      Required To Find:

      Fix for the compile error

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: The compiler finds two default methods with the same signature
      Step 2: C must override hello()
      Step 3: Inside it call A.super.hello() or B.super.hello() or write new code
      Final Answer: public String hello() { return A.super.hello() + B.super.hello(); }

      Approach note: The class always wins over interface defaults; otherwise you must resolve it manually.

      Example 03 · Intermediate

      Make class Person encapsulated so that age can never be negative.

      Given Data:
        Required To Find:

        Private field with validated setter

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Declare age as private
        Step 2: Add a public getter getAge()
        Step 3: Add setAge(int age) that throws IllegalArgumentException when age < 0
        Final Answer: class Person { private int age; public int getAge() { return age; } public void setAge(int age) { if (age < 0) throw new IllegalArgumentException("age < 0"); this.age = age; } }

        Approach note: Validation inside the setter keeps the object always valid.

        Example 04 · Basic

        Interface Shape { double area(); }. Class Circle implements it with radius 7. What is area using Math.PI * r * r (approx)?

        Given Data:
          Required To Find:

          Numeric area

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Circle must implement area()
          Step 2: r = 7 → 49π
          Step 3: 49 * 3.1416 ≈ 153.94
          Final Answer: ≈ 153.94 (49 * Math.PI)

          Approach note: A class that implements an interface must implement every abstract method.

          Real-world applications

          Java

          Using Java Abstraction & Interfaces in real projects

          Database drivers (JDBC interfaces), Spring services, plug-in architectures, API design and library packaging.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: An abstract class must have at least one abstract method.

          Why this is wrong: A class may be abstract only to stop instantiation.

          ✅ Verified Truth: The reverse is true: a class with an abstract method must be abstract.

          ⚠️ Exam Tip: Remember the direction of the rule.

          ❌ Myth: Interfaces cannot contain any code.

          Why this is wrong: Since Java 8 they can have default and static methods; Java 9 added private methods.

          ✅ Verified Truth: Interfaces hold contracts and may include a little shared behaviour.

          ⚠️ Exam Tip: Mention default methods in the abstract vs interface answer.

          ❌ Myth: protected means visible only to subclasses.

          Why this is wrong: protected also gives access inside the same package.

          ✅ Verified Truth: protected = package + subclasses.

          ⚠️ Exam Tip: Draw the access table.

          ❌ Myth: Encapsulation and abstraction are the same.

          Why this is wrong: One hides data, the other hides implementation.

          ✅ Verified Truth: Encapsulation = private data + public methods; abstraction = abstract class or interface.

          ⚠️ Exam Tip: Give one example for each.

          Revision notes

          Abstraction hides implementation details and shows only essential features. In Java it is achieved with abstract classes and interfaces. This chapter also covers encapsulation, packages and access modifiers, which together control how code is organised and protected.

          High-Yield Quick Revision Points

          1. Abstract class: cannot be instantiated; can have abstract and concrete methods, fields and constructors.
          2. abstract cannot combine with final, private or static (for methods).
          3. Interface: public abstract methods, public static final fields, plus default, static and private methods.
          4. A class implements many interfaces but extends one class; conflicting defaults must be resolved with X.super.method().
          5. Abstract class = shared state and code (IS-A); interface = capability contract (CAN-DO).
          6. Encapsulation = private fields + validated public getters/setters; immutable = final class, final fields, no setters.
          7. Package = namespace and folder; package statement first; java.lang is auto-imported; import * skips sub-packages.
          8. Access: private (class), default (package), protected (package + subclasses), public (everywhere).

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which of these can have a constructor?

          Question 2 · MCQ (Interview / semester)

          Variables declared in an interface are implicitly:

          Question 3 · MCQ (Interview / semester)

          Which access modifier allows access in the same package and in subclasses?

          Question 4 · MCQ (Interview / semester)

          Which combination is illegal?

          Question 5 · MCQ (Interview / semester)

          What must be the first statement of a Java source file with a package?

          Question 6 · MCQ (Interview / semester)

          Which package is imported automatically?