MST

星途 面试题库

面试题:Java多态重载中类型转换与方法选择

考虑以下Java代码片段: ```java class Shape { public void draw() { System.out.println("Drawing a shape"); } } class Circle extends Shape { @Override public void draw() { System.out.println("Drawing a circle"); } public void draw(int radius) { System.out.println("Drawing a circle with radius " + radius); } } class Rectangle extends Shape { @Override public void draw() { System.out.println("Drawing a rectangle"); } public void draw(int width, int height) { System.out.println("Drawing a rectangle with width " + width + " and height " + height); } } public class Main { public static void main(String[] args) { Shape shape1 = new Circle(); Shape shape2 = new Rectangle(); // 如果要调用Circle类中带参数的draw方法和Rectangle类中带参数的draw方法,应该如何进行类型转换并调用?请写出代码,并解释为什么要这样做。
47.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
public class Main {
    public static void main(String[] args) {
        Shape shape1 = new Circle();
        Shape shape2 = new Rectangle();
        // 调用Circle类中带参数的draw方法
        if (shape1 instanceof Circle) {
            Circle circle = (Circle) shape1;
            circle.draw(5);
        }
        // 调用Rectangle类中带参数的draw方法
        if (shape2 instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) shape2;
            rectangle.draw(10, 20);
        }
    }
}

解释

  1. instanceof关键字:在Java中,由于shape1shape2的声明类型是Shape,而实际类型分别是CircleRectangle。在调用子类特有的方法(如Circledraw(int radius)Rectangledraw(int width, int height))之前,需要先判断对象的实际类型是否是对应的子类,instanceof关键字用于此目的。如果直接进行类型转换而不判断,当对象实际类型与转换类型不匹配时,会抛出ClassCastException
  2. 类型转换:通过(Circle) shape1(Rectangle) shape2Shape类型的引用转换为具体的子类类型,这样才能访问到子类特有的方法。因为Shape类中并没有定义带参数的draw方法,只有通过转换为具体子类类型,才能调用到这些子类扩展的方法。