菜鸟新学Java,自己编了个小程序想试试继承、接口、上转型和多态这几个特性。但程序运行的时候总有异常,我也看不出哪里有问题,求教了。上代码:
public class Test {
    public static void main(String[] args)
    {
        Kid John=new Kid(7);
        Man[] one=new Man[0];
        one[0]=John;
        one[1]=new Man(21);
        /**运行时会说上面那两句那里
         *  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
         */
        for(Man e: one) {
            e.getAge();
        }
    }}//declare an interface C with a function getAge()
interface C {
    void tellAge();
}
//declare a class man which implements the interface C
class Man implements C {
    public Man(int a) {
        age=a;
    }
    public void tellAge() {
        System.out.println("This man's age is: "+age);
    }
    public int getAge() {
        return age;
    }    private int age;
}
//delare a class which extends the class man
class Kid extends Man {
    public Kid(int a) {
        super(a);
    }    @Override
    public void tellAge() {
        if(super.getAge()>18) {
            System.out.println("this kid has grown up");
        } else {
            System.out.println("this kid's age is: "+super.getAge());
        }
    }
}

解决方案 »

  1.   

    Man[] one=new Man[0];你的one根本没有空间,怎么放one[0]和one[1]啊至少应该写成
    Man[] one=new Man[2];
      

  2.   

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    下标越界
    Man[] one=new Man[0];one[1]=new Man(21);  //one[1]肯定要报错的
      

  3.   

    Man[] one=new Man[0];
            one[0]=John;
            one[1]=new Man(21);
     for(Man e: one) {
                e.getAge();
            }改为Man[] one=new Man[2];
            one[0]=John;
            one[1]=new Man(21);
     for(Man e: one) {
                e.tellAge();
            }
      

  4.   

    其他的没错,你的man对象数组初始化错误
    Man[] one=new Man[2];
            one[0]=John;
            one[1]=new Man(21);
      

  5.   


    public static void main(String[] args)
        {
            Kid John=new Kid(7);
            Man[] one=new Man[2];
            one[0]=John;
            one[1]=new Man(21);
            for(Man e: one) {
                e.tellAge();
            }
        }
      

  6.   

      Man[] one=new Man[0];
    哎 无语了 这句话说明你的数组大小为0啊!!
    Man[] one=new Man[2];这个说明数组有两个元素
      

  7.   

    不小心搞错了,调试的时候改了一下发上来的时候忘记改过来了。其实我原本写的是:Man[] one=new Man[1];真是傻了,今天看了好久没看出来
      

  8.   

    super.getAge()
    这不算错,但是可能之后会引起错误
    而且写在这里没啥用
      

  9.   

    Man[] one=new Man[0];
    数组长度只有0个,放不下2个元素,因此报告数组越界异常
      

  10.   

    Man[] one=new Man[1];
    楼主想当然以为这个可以放下两个数吗 不对的  要想放下两个数必须 是 Man[] one=new Man[2];因为java数组默认最后一个元素是\,不是你要放的元素 也就是说你要是想放n个元素,就必须申请n+1个大小的空间,所以会报异常的  就是数组声明的小问题 楼主加油