//此题根据参数个数的不同,欲通过动态绑定的方法,计算,正方形,或长方形的面积 //如果参数个数不正确,将处理异常
import chapter.e2.Myarea; //导入接口 //----------------------------------------------------------- class Realize implements Myarea //接口类 { public void area(int length) { System.out.println("正方形面积为:" + length*length); }
public void area(int length, int width) { System.out.println("长方形面积为:" + length*width); } } //------------------------------------------------------------ //以下两个类继承上面的接口类 class Rectangle extends Realize { int length; int width;
Rectangle(int length, int width) { this.length = length; this.width= width; } };
class Square extends Realize { int length; Square(int length) { this.length = length; } }; //-------------------------------------------------------------- class AreaDemo { public static void main(String args[]) { try { if (args.length == 0) { throw new ArrayIndexOutOfBoundsException("没有输入参数"); } if (args.length == 1) { Realize obj = new Square(Integer.parseInt(args[0])); obj.area(Integer.parseInt(args[0])); } else { Realize obj = new Rectangle(Integer.parseInt(args[0]), Integer.parseInt(args[1])); obj.area(Integer.parseInt(args[0]), Integer.parseInt(args[1])); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e); }
catch (NumberFormatException s) { System.out.println("字符格式转化错误"); } } }; //开始编译: //D:\java>javac -classpath chapter.e2 AreaDemo.java //编译结果为下列说明: //AreaDemo.java:4: package chapter.e2 does not exist //import chapter.e2.Myarea; //导入接口 ^ //AreaDemo.java:6: cannot find symbol //symbol: class Myarea //class Realize implements Myarea //接口类 ^ //2 errors 希望高手能给我解答一下,谢谢!