Consider the following Java code:
public class Shape {
protected double area;
public Shape(double area) {
this.area = area;
}
public double getArea() {
return area;
}
public String displayShape() {
return "This is a shape";
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
super(Math.PI * radius * radius);
this.radius = radius;
}
@Override
public double getArea() {
return super.getArea();
}
public double getRadius() {
return radius;
}
@Override
public String displayShape() {
return "This is a circle";
}
}
Explain the concepts of inheritance and polymorphism demonstrated in the given code.
Inheritance: Inheritance is a key concept in object-oriented programming where a new class inherits properties and behaviors (methods) from an existing class. In the given code, the class Circle
is inheriting from the class Shape
. This means that the Circle
class has access to the properties and methods defined in the Shape
class, and it can also override these methods with its own implementation, allowing for code reuse and extension.
Polymorphism: Polymorphism is the ability of a subclass to redefine a method that is already defined in its superclass. In the given code, the Circle
class overrides the getArea
method from the Shape
class. This allows instances of Circle
to use the overridden getArea
method instead of the one defined in Shape
, demonstrating polymorphism.
Additionally, the displayShape
method is also overridden in the Circle
class. This allows instances of Circle
to use the overridden displayShape
method instead of the one defined in Shape
, further demonstrating polymorphism.
Overall, the code demonstrates how inheritance and polymorphism work together to create a more flexible and reusable object-oriented design.