Bala Krishna Bala Krishna - 1 year ago 77
Java Question

Will typecasting of null throw an error or exception in java (android)?

Is it advised to use typecasting of null to specific objects and using it in the constructor decreases the quality of code in anyway
I'm doing this in the below scenario.

The Actual constructor are like this:

SomeListener(Fragment1 fragment1,String someValue){}

SomeListener(Fragment2 fragment2,String someValue){}

Now when I use this constructor as follows I am getting an error that it is ambiguous and it matches both of above constructors

SomeListener sml = new SomeListener(null,"value");

So what I did was this:

SomeListener sml = new SomeListener((Fragment2)null,"value");

Is this good way of coding or is there a better solution ? Will this solution cause any issue in runtime?

Answer Source

This is described in JLS Sec 4.1:

The null reference can always be assigned or cast to any reference type.

So no, it won't throw an exception.

An alternative (I won't claim better) way to do this is to provide static factory methods for the different constructors:

static SomeListener newFragment2Listener(String str) {
  return new SomeListener((Fragment2) null, str);

All this does is to hide the casting from users of the class, though. I always find casting a bit ugly; whether that ugliness is a reason for another method is up to you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download