空点异常|枚举构造函数中的“this”导致 NPE
public class Test {
public static void main(String[] args) {
Platform1 p1=Platform1.FACEBOOK; //giving NullPointerException.
Platform2 p2=Platform2.FACEBOOK; //NO NPE why?
}
}
enum Platform1{
FACEBOOK,YOUTUBE,INSTAGRAM;
Platform1(){
initialize(this);
};
public void initialize(Platform1 platform){
switch (platform) {
//platform is not constructed yet,so getting `NPE`.
//ie. we doing something like -> switch (null) causing NPE.Fine!
case FACEBOOK:
System.out.println("THIS IS FACEBOOK");
break;
default:
break;
}
}
}
enum Platform2{
FACEBOOK("fb"),YOUTUBE("yt"),INSTAGRAM("ig");
private String displayName;
Platform2(String displayName){
this.displayName=displayName;
initialize(this);
};
public void initialize(Platform2 platform){
switch (platform.displayName) {
//platform not constructed,even No `NPE` & able to access its properties.
//switch (null.displayName) -> No Exception Why?
case "fb":
System.out.println("THIS IS FACEBOOK");
break;
default:
break;
}
}
}
谁能解释一下为什么有在里面,但不在.在第二种情况下,我们如何能够在构造对象之前访问枚举对象及其属性?NullPointerException
Platform1
Platform2