java裏null強轉為某個類會報錯嗎?
阿新 • • 發佈:2018-12-06
this nbsp string private cor getc inter mil poi 1.定義一個User類如下:
2.測試null是否可以轉為User類
也就是輸出值為null,所以null可以強轉為某個類編譯不報錯,但是強轉後還是為null
3.如果null來調用方法則會報錯
報空異常
/**
* @author lizhibiao
* @date 2018/11/27 17:21
*/
public class User
{
private String userName;
private int age;
private int cutScore;
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getCutScore() {
return cutScore;
}
public void setCutScore(int cutScore) {
this.cutScore = cutScore;
}
}
2.測試null是否可以轉為User類
public class Test運行結果如下:null
{
public static voidmain(String[] args)
{
User user = (User)null;
System.out.println(user);
}
}
也就是輸出值為null,所以null可以強轉為某個類編譯不報錯,但是強轉後還是為null
3.如果null來調用方法則會報錯
public class Test運行結果如下:Exception in thread "main" java.lang.NullPointerException at str.Test.main(Test.java:11)
{
public static void main(String[] args)
{
User user = (User)null;
System.out.println(user.getUserName());}
}
報空異常
java裏null強轉為某個類會報錯嗎?