java 静态方法 异常_java空指针异常与静态方法

从一道经典面试题说起,

public class HaHa {

public static void haha(){

System.out.println("haha");

}

public static void main(String[] args){

((HaHa)null).haha();

}

}

打印结果 haha。

这段题考查两点知识,java的空指针异常和静态方法。

1,NullPointerException

Thrown when an application attempts to use null in a case where an object is required. These include:

Calling the instance method of a null object.

Accessing or modifying the field of a null object.

Taking the length of null as if it were an array.

Accessing or modifying the slots of null as if it were an array.

Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.

这段话表明只有在使用空对象时,才会抛出空指针异常。而上面的写法并没有调用对象的方法。

2,static修饰的方法是静态方法。静态方法可通过类来调用,也可通过对象调用,即使使用对象调用,它的入口也在类上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值