Have a question?
Message sent Close
View Categories

What is Abstraction? 

What is Abstraction? 

📄
filename.js
1. Abstract Classes:

// Abstract class

abstract class Shape {

    // Abstract method (does not have a body)

    abstract void draw();

    // Regular method

    void description() {

        System.out.println("This is a shape.");

    }

}

// Concrete subclass

class Circle extends Shape {

    // Providing implementation of the abstract method

    @Override

    void draw() {

        System.out.println("Drawing a circle.");

    }

}

public class Main {

    public static void main(String[] args) {

        Shape shape = new Circle(); // Cannot instantiate abstract class

        shape.draw(); // Outputs: Drawing a circle.

        shape.description(); // Outputs: This is a shape.

    }

}

📄
filename.js
// Interface

interface Drawable {

    void draw();

}

// Concrete class implementing the interface

class Rectangle implements Drawable {

    @Override

    public void draw() {

        System.out.println("Drawing a rectangle.");

    }

}

public class Main {

    public static void main(String[] args) {

        Drawable drawable = new Rectangle();

        drawable.draw(); // Outputs: Drawing a rectangle.

    }

}