Java 类、对象与枚举类型深入探究
1. 避免程序崩溃: FullName 类的处理
在 Java 编程中,我们有时会遇到程序崩溃的情况。例如以下代码:
FullName name = new FullName();
// Get the length of the full name.
len = name.getLength();
这段代码在运行时会崩溃,原因是在调用 getLength 方法之前, name 对象的字段还未引用 String 对象。为了避免程序崩溃,有两种解决方法。
1.1 使用 if 语句判断字段是否为 null
public int getLength()
{
int len = 0;
if (lastName != null)
len += lastName.length();
if (firstName != null)
len += firstName.length();
if (middleName != null)
len += middleName.length();
return len;
}
超级会员免费看
订阅专栏 解锁全文

68

被折叠的 条评论
为什么被折叠?



