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;
}
}
}
Can anyone explain me why there is NullPointerException
in Platform1
but not in Platform2
. How in the second case we are able to access the enum object and its properties, even before the object is constructed?