Casting to Button is redundant - Why?

sandalone picture sandalone · Mar 1, 2012 · Viewed 15.2k times · Source

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.

Answer

Boris Strandjev picture Boris Strandjev · Mar 1, 2012

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.