Monday, October 17, 2016

What is java type casting

In android programming with java you will frequently encounter type casting. Since java class can extends another class, this another class can also be casted to its subclass.
Let's see the example code :
package com.example.myapplication.alert;

/**
 * Created by SONY on 17/10/2016.
 */
public class Child extends Father {
    
}

From the code above Child is called a subclass and Father is called a superclass. There is time you need to cast a superclass to its subclass, let's see one example :
 public void createPeople() {
        ArrayList<Father> list = new ArrayList<Father>();
        Father father = new Father();
        Child child = new Child();
        list.add(father);
        list.add(child);
        int size = list.size();
        for(int i = 0; i < size ; i++) {
            Father father1 = list.get(i);
            if(father1 instanceof Child){
                Child child1 = (Child) father1;
            }
        }
    }

Look at line 11, here father1 is type casted to Child, at line 10 we have checked wether father1 is an object instance of Child. so at line 11 now it is safe to cast to its subclass. If we remove line 10, we will not be sure wether father1 is a Child, if not of type Child,  a TypeCastException will be raised. Let's see type casting example in android programming. Look at the activity class code below :
 package com.example.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.btnLogin);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }
}
In android code above, at line 14, findViewById(R.id.btnLogin); return value is a type of View (look at reference here ), but then is casted to type Button. Since Button extends View , see reference  here , this return value of findViewById could be a Button type. But you should make sure that the id R.id.btnLogin  is referring to is the right Button widget in layout xml file. If it does not correctly refer to Button widget in xml layout, a ClassCastException will be raised that will make your app force close.

Thank you for visiting our website. Just comment below if you have any question to ask.

No comments:

Post a Comment