Java Programming Day 12

HimanshiHimanshi
4 min read

🌟 Java Day 12 β€” Mastering Abstract Classes & Interfaces

πŸ“Œ Introduction

Welcome to Day 12 of my Java journey! Today, I explored two powerful OOP concepts: Abstract Classes and Interfaces. These are essential for building flexible, reusable, and maintainable software by enforcing rules on method implementations while allowing code sharing and multiple behaviors.


🧱 Concept 1: Abstract Classes

πŸ” What is an Abstract Class?

  • Cannot be instantiated directly.

  • Contains both abstract methods (without body) and concrete methods (with implementation).

  • Used to share common behavior while requiring subclasses to implement specific methods.

βœ… Program: Abstract Class Implementation

javaCopyEdit
public abstract class Shape {
    // Abstract method to calculate area; subclasses must implement this
    abstract double area();

    // Concrete method shared by all shapes
    void display() {
        System.out.println("This is a shape");
    }
}

// Circle class extends Shape and implements area calculation
public class Circle extends Shape {
    double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}

// Rectangle class extends Shape and implements area calculation
public class Rectangle extends Shape {
    double length;
    double width;

    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    double area() {
        return length * width;
    }
}

// Triangle class extends Shape and implements area calculation
public class Triangle extends Shape {
    double base;
    double height;

    Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    @Override
    double area() {
        return 0.5 * base * height;
    }
}

// Main class to run the program
public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(5);
        Triangle triangle = new Triangle(3, 6);
        Rectangle rectangle = new Rectangle(6, 4);

        // Display common info from Shape class
        circle.display();
        triangle.display();
        rectangle.display();

        // Print areas calculated by each subclass
        System.out.println("Circle Area: " + circle.area());
        System.out.println("Triangle Area: " + triangle.area());
        System.out.println("Rectangle Area: " + rectangle.area());
    }
}

πŸ” Explanation:

  • Shape is abstract β€” no direct instances allowed.

  • Abstract method area() must be implemented by subclasses.

  • Concrete method display() is inherited by all subclasses.

  • Circle, Rectangle, Triangle provide their own area() implementations.

  • Main creates subclass objects and demonstrates polymorphism by calling their area() methods.


βš™οΈ Concept 2: Interfaces

πŸ” What is an Interface?

  • A blueprint for classes containing only abstract methods (before Java 8).

  • Supports multiple inheritance β€” classes can implement multiple interfaces.

  • Enforces a contract: implementing classes must provide all interface methods.

βœ… Program: Interface with Prey and Predator Behavior

javaCopyEdit// Interface declaring hunt behavior for predators
public interface Predator {
    void hunt();
}

// Class representing prey animals with a flee behavior
public class Prey {
    void flee() {
        // Default flee behavior (can be overridden)
    }
}

// Fish is both prey and predator: extends Prey and implements Predator
public class Fish extends Prey implements Predator {
    @Override
    public void flee() {
        System.out.println("*The fish is running away*");
    }

    @Override
    public void hunt() {
        System.out.println("The fish is hunting");
    }
}

// Rabbit is prey only; overrides flee behavior
public class Rabbit extends Prey {
    @Override
    public void flee() {
        System.out.println("*The rabbit is running away*");
    }
}

// Hawk is predator only; implements hunt behavior
public class Hawk implements Predator {
    @Override
    public void hunt() {
        System.out.println("The hawk is hunting");
    }
}

// Main class to demonstrate behaviors
public class Main {
    public static void main(String[] args) {
        Rabbit rabbit = new Rabbit();
        Hawk hawk = new Hawk();
        Fish fish = new Fish();

        rabbit.flee();  // Rabbit fleeing
        hawk.hunt();    // Hawk hunting
        fish.flee();    // Fish fleeing
        fish.hunt();    // Fish hunting
    }
}

πŸ” Explanation:

  • Predator interface defines hunt() method β€” all implementers must define it.

  • Prey class provides flee() method, which subclasses may override.

  • Fish inherits from Prey and implements Predator, so it has both flee() and hunt().

  • Rabbit only overrides flee().

  • Hawk only implements hunt().

  • This models real-world behaviors using interfaces and inheritance.


πŸ“ Key Takeaways

  • Abstract Classes:

    • Can have both abstract and concrete methods.

    • Cannot instantiate abstract classes directly.

    • Ideal for sharing code and forcing subclasses to implement key methods.

  • Interfaces:

    • Define method contracts without implementation (pre-Java 8).

    • Support multiple inheritance of behavior.

    • Enforce method implementation on unrelated classes.

  • When to use:

    • Abstract classes for closely related classes sharing code.

    • Interfaces to enforce behavior across unrelated classes or support multiple behaviors.

      🏁 Conclusion

Day 12 was all about abstraction and interfaces β€” two cornerstones of Java OOP that make code flexible, extensible, and maintainable. Abstract classes allow partial implementation and enforce method rules, while interfaces enable multiple behaviors and strict contracts.

Understanding these concepts is essential for advanced Java programming and real-world software design. This session helped me grasp how to model complex relationships and behaviors cleanly using Java’s OOP features.

1
Subscribe to my newsletter

Read articles from Himanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Himanshi
Himanshi

Hi! I'm a curious and self-driven programmer currently pursuing my BCA πŸŽ“ and diving deep into the world of Java β˜• from Day 1. I already have a foundation in programming, and now I'm expanding my skills one concept, one blog, and one project at a time. I’m learning Java through Bro Code’s YouTube tutorials, experimenting with code, and documenting everything I understand β€” from basic syntax to real-world applications β€” to help others who are just starting out too. I believe in learning in public, progress over perfection, and growing with community support. You’ll find beginner-friendly Java breakdowns, hands-on code snippets, and insights from my daily coding grind right here. πŸ’‘ Interests: Java, Web Dev, Frontend Experiments, AI-curiosity, Writing & Sharing Knowledge πŸ› οΈ Tools: Java β€’ HTML/CSS β€’ JavaScript β€’ Python (basics) β€’ SQL 🎯 Goal: To become a confident Full Stack Developer & AI Explorer πŸ“ Based in India | Blogging my dev journey #JavaJourney #100DaysOfCode #CodeNewbie #LearnWithMe