• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Compare View type with Button type !

Accolade

Lurker
Hi friends,

Below is a very simple code :

-----------------------------------------------------
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

static final String TAG_I = "LOG_I";
private Button btn;

aOverride
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Log.i(TAG_I, "onCreate : Test !");

btn = (Button) findViewById(R.id.button1);

btn.setOnClickListener(this);

}

aOverride
public void onClick(View v) {

if (v == btn)
{
Toast.makeText(this, "Click ok", Toast.LENGTH_LONG).show();
}
}
-----------------------------------------------------

In this code, the type of btn is Button and the type of v is View.
In the Android Framework, Button extends TextView and TexteView extends View, ok, but there :

if (v == btn)

we compare an object of type Button with an object of type View, how is this possible?

Possible answer: Button extends TextView and TextView extends View, so btn also View type? Right ?
 
That's the magic of polymorphism. In object relationship terms, then if class A extends B, then A 'IS-A' B.
If you declare two variables of the different types, you can assign them to each other, but when the code runs there is only one object created in memory. Think of them as aliases to the same object.

Consider the following code:

Code:
public class B {

    private class A extends B {
    }

    A aObj1 = new A();    // Ok
    B bObj1 = new B();    // Ok
    B bObj2 = new A();   // Ok, because A Is-a B
    B bObj3 = aObj1;       // Ok, because A Is-a B. bObj3 becomes an 'alias' to aObj1. Only one object instance is created
    A aObj2 = new B();   // Not Ok, can't declare an A object and assign it to B, because B is NOT an A
}

Note also that by using a cast (Button) operator, it's possible to coerce an object into something else. In using this you are asking the compiler to trust that you know what you're doing. Getting it wrong will cause a ClassCastException at runtime. but it works if the types of variables are consistent, as in the Button/View relationship.

So in your code, then findViewById() actually returns an object of type View. But you are saying, look I know this object is actually a Button (which is also a View), so it's perfectly ok to cast it into a Button. In fact this is technically called a 'downcast' because you are casting down the class inheritance hierarchy.
You would have a problem if the object returned was not actually a Button, but an EditText, in that case you'd get a ClassCastException.
 
Last edited by a moderator:
Back
Top Bottom