面试题答案
一键面试- 接口多态性概念:
- 在Java中,接口多态性是指一个接口可以有多个不同的实现类,程序可以根据对象的实际类型来调用相应实现类的方法。这是通过接口类型的变量来引用不同实现类的对象,从而在运行时决定调用哪个实现类的方法。
- 代码示例:
// 定义接口
interface Shape {
double calculateArea();
}
// 实现接口的第一个类
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// 实现接口的第二个类
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 PolymorphismDemo {
public static void main(String[] args) {
// 接口类型变量引用Circle对象
Shape circle = new Circle(5.0);
// 接口类型变量引用Rectangle对象
Shape rectangle = new Rectangle(4.0, 6.0);
// 调用各自实现类的calculateArea方法,体现多态性
System.out.println("Circle area: " + circle.calculateArea());
System.out.println("Rectangle area: " + rectangle.calculateArea());
}
}
在上述代码中,Shape
是一个接口,Circle
和Rectangle
是实现了Shape
接口的两个不同类。在main
方法中,通过Shape
接口类型的变量分别引用Circle
和Rectangle
类的对象,并调用calculateArea
方法,这就是接口多态性的体现。根据对象实际类型的不同,调用的是相应实现类的calculateArea
方法。