MST

星途 面试题库

面试题:Java接口实现类的多态性相关问题

在Java中,定义一个接口`Shape`,包含方法`calculateArea`。然后定义两个类`Circle`和`Rectangle`实现该接口。请阐述如何利用接口实现多态,并编写代码示例展示在一个方法中接收`Shape`类型参数,根据传入对象的不同调用对应的`calculateArea`方法。
10.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 接口定义
    public interface Shape {
        double calculateArea();
    }
    
  2. 实现类定义
    • 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;
        }
    }
    
  3. 多态实现及代码示例
    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方法。CircleRectangle类实现了该接口,并各自实现了calculateArea方法。printArea方法接收Shape类型的参数,在main方法中,分别创建CircleRectangle对象并传入printArea方法,根据传入对象的实际类型调用对应的calculateArea方法,这就是接口实现多态的体现。