0

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?

5
  • The way you've suggested is correct. It tells the compiler which version of the constructor you want to use. Commented Oct 26, 2016 at 12:23
  • 2
    Have you tried casting null like that? What happened? (It's fine.) You can easily tell whether it will throw an exception or not by just trying it - or reading the JLS, of course. Commented Oct 26, 2016 at 12:23
  • have you considered doing a builder pattern, then you wouldn't have to pass nulls into the constructor, you will build the listener only with the "someValue" Commented Oct 26, 2016 at 12:39
  • @AshFrench can you share an example..I'll try it out Commented Oct 26, 2016 at 12:58
  • @AshFrench Builder isn't necessary here, and would make things overly complicated; static factory methods would be sufficient. Commented Oct 26, 2016 at 13:16

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.