Here are some additional points to consider before writing the code:
In Java, we use the abstract keyword to define abstract classes and methods. Abstract methods have no implementation and are defined without braces and followed by a semicolon.
An abstract class cannot be instantiated, which means we cannot create an object of an abstract class. We can only create objects of its concrete subclasses.
A concrete class is a regular class that provides the implementation details for all the abstract methods inherited from its abstract superclass.
In Java, we use the @Override annotation to indicate that a method is intended to override a method in the superclass. This is optional but recommended to avoid accidental overloading.
Keeping these points in mind, we can now proceed with
writing the code.
Source Code..
Here is the implementation of the code:
import java.lang.Math;
abstract class Shape {
public abstract
void RectangleArea(int length, int breadth);
public abstract
void SquareArea(int side);
public abstract
void CircleArea(int radius);
}
class Area extends Shape {
@Override
public void
RectangleArea(int length, int breadth) {
int area =
length * breadth;
System.out.println("Area of Rectangle: " + area);
}
@Override
public void
SquareArea(int side) {
int area =
side * side;
System.out.println("Area of Square: " + area);
}
@Override
public void
CircleArea(int radius) {
double area =
Math.PI * radius * radius;
System.out.println("Area of Circle: " + area);
}
}
public class Main {
public static void
main(String[] args) {
Area areaObj =
new Area();
areaObj.RectangleArea(10, 20);
areaObj.SquareArea(15);
areaObj.CircleArea(5);
}
}
Code Explanation:
In this code, we have defined an abstract class Shape with
three abstract methods RectangleArea, SquareArea, and CircleArea. We have also
defined a concrete class Area that extends the Shape class and provides the
implementation details for all the three methods. The RectangleArea method
takes two parameters, length and breadth, and calculates the area of the
rectangle by multiplying these two parameters. The SquareArea method takes one
parameter, side, and calculates the area of the square by multiplying the side
with itself. The CircleArea method takes one parameter, radius, and calculates
the area of the circle using the formula pi times radius squared.
Finally, the main program creates an object of the Area class and calls all the three methods to calculate the area of a rectangle, square, and circle. The program outputs the results of the calculations using the System.out.println() statement.
The use of abstract classes and methods ensures that the
subclasses implement these methods to provide their functionality. The
implementation of the Area class uses inheritance to provide the implementation
details for the Shape class's abstract methods.
No comments:
Post a Comment