- 论坛徽章:
- 0
|
作业贴?
给楼主一个参考吧:
Shape.java
abstract class Shape {
public abstract void showShape();
} |
Square.java
public class Square extends Shape {
public void showShape() {
System.out.print("The Square:");
}
public void calc(long a,long b) {
System.out.println(a * b);
}
} |
Triangle.java
public class Triangle extends Shape {
public void showShape() {
System.out.print("The Triangle:");
}
public void calc(long a,long b) {
System.out.println(a * b / 2);
}
} |
Test.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
Shape triangle = new Triangle();
Shape square = new Square();
// Shape circular = new Circular(); //这个试试自己去实现
Triangle a = new Triangle();
Square b = new Square();
// Circular c = new Circular(); //这个试试自己去实现
doShowIt(triangle, 2, 4);
doShowIt(square, 2, 4);
// doShowIt(circular, 2); //这个试试自己去实现
System.out.println();
doShowIt(a, 2, 4);
doShowIt(b, 2, 4);
// doShowIt(c, 2); //这个试试自己去实现
}
public static void doShowIt(Shape shape, long a, long b) {// 这里,用抽象类,再来点反射
shape.showShape();
try {
// 参数值
Object[] value = new Object[] { a, b };
// 参数类型
Class parm[] = new Class[] { long.class, long.class };
// 得到类
Class c = shape.getClass();
// 创建类对象
Object object = c.newInstance();
// 得到方法对象
Method method = object.getClass().getDeclaredMethod("calc", parm);
// 调用方法
method.invoke(object, value);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
|
|
|