I've just came across this interesting message from the compiler and I do not know why is it happening. Here is the case
Example 1.
Button test = (Button) findViewById(R.id.someButtonId);
test.setOnClickListener(this);
Example 2.
findViewById(R.id.someButtonId).setOnClickListener(this);
In the first example, I need to cast an object returned by findViewById
to Button
. In the second example, I do not have to cast returned object because I did not use another Button
class object. If I try to cast it via
((Button)findViewById(R.id.someButtonId)).setOnClickListener(this);
I will get the warning Casting findViewById(R.id.someButtonId) to Button is redundant
.
Why is this happening? I am not trying to remove cast warning. I want to know the logic behind this and why casting is not needed if I do not try to initialize another object with the object returned by findViewById
.
The reason why you get this is because findViewById
returns View
and this class already defines the method setOnClickListener
. This means that even without doing the cast you can set the listener. Thus your cast is redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With