1. Are you ready for the Galaxy S20? Here is everything we know so far!

Compare View type with Button type !

Discussion in 'Android Development' started by Accolade, Feb 11, 2016.

  1. Accolade

    Accolade Lurker
    Thread Starter

    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;

    protected void onCreate(Bundle savedInstanceState) {

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

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



    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 ?

    1. Download the Forums for Android™ app!


  2. Deleted User

    Deleted User Guest

    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 (Text):
    2. public class B {
    4.     private class A extends B {
    5.     }
    7.     A aObj1 = new A();    // Ok
    8.     B bObj1 = new B();    // Ok
    9.     B bObj2 = new A();   // Ok, because A Is-a B
    10.     B bObj3 = aObj1;       // Ok, because A Is-a B. bObj3 becomes an 'alias' to aObj1. Only one object instance is created
    11.     A aObj2 = new B();   // Not Ok, can't declare an A object and assign it to B, because B is NOT an A
    12. }
    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.
    #2 Deleted User, Feb 11, 2016
    Last edited by a moderator: Feb 11, 2016

Share This Page