Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to Button is redundant - Why?

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.

like image 374
sandalone Avatar asked Feb 02 '23 07:02

sandalone


1 Answers

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.

like image 134
Boris Strandjev Avatar answered Mar 17 '23 00:03

Boris Strandjev