package com.heima.fan;
public class Demo2 {
public static void main(String[] args) {
compareDogs();
}
public static void compareDogs(){
Dog dog1 = new Dog("哈士奇", 5);
Dog dog2 = new Dog("哈士奇", 5);
Dog dog3 = null; //dog3 是空值
System.out.println("这两只狗一样吗?" + dog1.equals(dog2));
System.out.println("这两只狗一样吗?" + dog1.equals(dog3));
}
}
class Dog{
String breed;
int age;
Dog(String breed, int age){
this.breed = breed;
this.age = age;
}
@Override
public boolean equals(Object obj){
if (obj != null && obj instanceof Dog) // 1
{
Dog anotherDog = (Dog) obj;
/*
* 如果两只狗的品种和年龄都一样,则返回 true
*/
return (breed.equals(anotherDog.breed) && age == anotherDog.age);
}
return false;
}
}
在注释 1 的那一句中,如果不检查 obj 是否为空,当传进来的参数 obj 为空时,是否会造成空指针(NullPointerException)异常?
也就是说,如果写成 if (obj instanceof Dog),是否有可能产生空指针异常? |
|