面试题答案
一键面试- 接口定义:
public interface Shape { double calculateArea(); }
- 实现类定义:
- Circle类:
public class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double calculateArea() { return Math.PI * radius * radius; } }
- Rectangle类:
public class Rectangle implements Shape { private double width; private double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } @Override public double calculateArea() { return width * height; } }
- 多态实现及代码示例:
public class ShapeTest { public static void printArea(Shape shape) { System.out.println("The area is: " + shape.calculateArea()); } public static void main(String[] args) { Shape circle = new Circle(5.0); Shape rectangle = new Rectangle(4.0, 6.0); printArea(circle); printArea(rectangle); } }
在上述代码中,Shape
接口定义了calculateArea
方法。Circle
和Rectangle
类实现了该接口,并各自实现了calculateArea
方法。printArea
方法接收Shape
类型的参数,在main
方法中,分别创建Circle
和Rectangle
对象并传入printArea
方法,根据传入对象的实际类型调用对应的calculateArea
方法,这就是接口实现多态的体现。