菜鸟新学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());
}
}
}
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());
}
}
}
Man[] one=new Man[2];
下标越界
Man[] one=new Man[0];one[1]=new Man(21); //one[1]肯定要报错的
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();
}
Man[] one=new Man[2];
one[0]=John;
one[1]=new Man(21);
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();
}
}
哎 无语了 这句话说明你的数组大小为0啊!!
Man[] one=new Man[2];这个说明数组有两个元素
这不算错,但是可能之后会引起错误
而且写在这里没啥用
数组长度只有0个,放不下2个元素,因此报告数组越界异常
楼主想当然以为这个可以放下两个数吗 不对的 要想放下两个数必须 是 Man[] one=new Man[2];因为java数组默认最后一个元素是\,不是你要放的元素 也就是说你要是想放n个元素,就必须申请n+1个大小的空间,所以会报异常的 就是数组声明的小问题 楼主加油