Abstraction
1. Abstract Classes
// Abstract class
abstract class Shape {
// Abstract method (no implementation)
abstract double area();
}
// Concrete subclass 1
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
// Implementing the abstract method area() for Circle
double area() {
return Math.PI * radius * radius;
}
}
// Concrete subclass 2
class Rectangle extends Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementing the abstract method area() for Rectangle
double area() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of concrete subclasses
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);
// Calling the area() method on objects of different concrete subclasses
double circleArea = circle.area();
double rectangleArea = rectangle.area();
// Displaying the results
System.out.println("Area of Circle: " + circleArea);
System.out.println("Area of Rectangle: " + rectangleArea);
}
}2. Interface

Last updated