Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for lengt...

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at com.wanglx.duotai.Practice_duotai.main(Practice_duotai.java:9)

public class Practice_duotai {
    public static void main(String[] args) {
        Traffic [] t=new Traffic[4];
        t[1]=new Car();
        t[2]=new Bicycle();
        t[3]=new Car();
        t[4]=new Bicycle();
        for(int i=0;i<4;i++) {
            t[i].drive();
        }
        
    }
}
class Traffic{
    public void drive() {
        System.out.println("前进");
    }
}
class Car extends Traffic{
    public void  drive() {
        System.out.println("很快");
    }
}
class Bicycle extends Traffic{
    public void drive() {
        System.out.println("很慢");
    }
}

这是我学习“多态”时,练习的简单代码,当时运行的时候idea给出了

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
    at com.wanglx.duotai.Practice_duotai.main(Practice_duotai.java:9)

这样的错误代码

这个异常是初学者比较常见的异常。
ArrayIndexOutOfBoundsException:注意这个单词,字面意思就是数组引用超出界限,也就是我们常说的越界问题。
比如,我们创建了一个数组 int a[] = new int[4] ;
那么数组a只能存放四个元素,而数组的下标是从0开始的,也就是说,a[3]就是最后一个元素。当你给a[4]赋值,或者使用a[4]的时候,就出现了ArrayIndexOutOfBoundsException异常
修改以后
 1 package com.wanglx.duotai;
 2 
 3 public class Practice_duotai {
 4     public static void main(String[] args) {
 5         Traffic [] t=new Traffic[4];
 6         t[0]=new Car();
 7         t[1]=new Bicycle();
 8         t[2]=new Car();
 9         t[3]=new Bicycle();     //这里要注意
10         for(int i=0;i<4;i++) {
11             t[i].drive();
12         }
13         
14     }
15 }
16 class Traffic{
17     public void drive() {
18         System.out.println("前进");
19     }
20 }
21 class Car extends Traffic{
22     public void  drive() {
23         System.out.println("很快");
24     }
25 }
26 class Bicycle extends Traffic{
27     public void drive() {
28         System.out.println("很慢");
29     }
30 }

 

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值