Monday, 8 April 2024

Abstract class in JAVA

 abstract class Shape {

    abstract double area(); // Abstract method to calculate area

    abstract double perimeter(); // Abstract method to calculate perimeter


    void display() {

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

    }

}


class Circle extends Shape {

    double radius;


    Circle(double radius) {

        this.radius = radius;

    }


    @Override

    double area() {

        return Math.PI * radius * radius;

    }


    @Override

    double perimeter() {

        return 2 * Math.PI * radius;

    }

}


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;

    }


    @Override

    double perimeter() {

        return 2 * (length + width);

    }

}


public class AbstractClassExample {

    public static void main(String[] args) {

        Circle circle = new Circle(5);

        System.out.println("Area of circle: " + circle.area());

        System.out.println("Perimeter of circle: " + circle.perimeter());


        Rectangle rectangle = new Rectangle(4, 6);

        System.out.println("Area of rectangle: " + rectangle.area());

        System.out.println("Perimeter of rectangle: " + rectangle.perimeter());


        circle.display();

        rectangle.display();

    }

}


No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...