面试题答案
一键面试- 接口体现多态性的机制:
- 在Java中,接口体现多态性主要通过以下方式:
- 定义规范:接口定义了一组方法的签名,但没有实现这些方法。不同的类可以实现同一个接口,按照接口的规范来提供不同的方法实现。
- 向上转型:可以将实现接口的类的实例赋值给接口类型的变量。这样,通过这个接口类型的变量调用接口方法时,实际执行的是具体实现类重写的方法,从而体现多态性。
- 在Java中,接口体现多态性主要通过以下方式:
- 代码示例:
- 首先定义一个接口:
public interface Shape {
double calculateArea();
}
- 然后定义两个实现该接口的类:
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
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 main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
System.out.println("Circle area: " + circle.calculateArea());
System.out.println("Rectangle area: " + rectangle.calculateArea());
}
}
在上述代码中,Circle
和Rectangle
类都实现了Shape
接口。通过Shape
接口类型的变量circle
和rectangle
,调用calculateArea
方法时,实际执行的是各自实现类中重写的方法,这就是接口体现多态性的具体表现。