酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Java:参照示例拓展 Rect 子类,用反射创建对象并重写方法

以下是一个 Java 示例代码,满足您的需求: ```java import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; class Rect { int length; int width; Rect(int length, int width) { this.length = length; this.width = width; } public int getArea() { return length * width; } } class Square extends Rect { Square(int sideLength) { super(sideLength, sideLength); } @Override public int getArea() { return sideLength * sideLength; } } public class Main { public static void main(String[] args) { try { Class<?> clazz = Class.forName(args[0]); Constructor<?> constructor = clazz.getConstructor(int.class); Object obj = constructor.newInstance(5); if (obj instanceof Rect) { Rect rect = (Rect) obj; System.out.println("Area: " + rect.getArea()); } } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } ``` 在上述代码中,我们创建了一个`Rect`类和它的子类`Square`,并重写了`getArea`方法。在`main`方法中,通过命令行参数传入类名,使用反射创建对象并调用`getArea`方法。运行时需要在命令行中提供类名作为参数。 ######[AI写代码神器 | 357点数解答 | 2024-10-30 12:49:21]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]