Explanation
This Java program demonstrates the fundamental concept of Single Inheritance. In inheritance, one class (the subclass) acquires the properties and behaviors of another class (the superclass).
- The Base Class (
Shape): We start by defining a class namedShape. This class acts as a template containing two attributes:lengthandbreadth. These represent the common properties that many geometric shapes share. - The Derived Class (
Rectangle): We then define a class namedRectangle. By using the keywordextends, we tell Java thatRectangleis a specialized type ofShape. Because of inheritance, theRectangleclass automatically "inherits" thelengthandbreadthvariables from theShapeclass without having to redefine them. - Specific Functionality: Inside the
Rectangleclass, we add a new variableareaand a methodcalculateArea(). This method uses the inherited attributes to compute the area. - Execution Logic: In the
mainmethod, we create an instance (object) of theRectangleclass. Even though we didn't definelengthorbreadthinside theRectangleclass block, we can access them through theRectangleobjectr. We assign values to these attributes, call the calculation method, and print the final result to the console.