a question about android video tutorial number 28

+3 bobby habib · January 19, 2015
Hi in the 28th tutorial (https://www.thenewboston.com/videos.php?cat=278&video=27362) i can't understand a bit of the code :(

TopSectionListener activityCommander;
    public interface TopSectionListener{
        public void createMeme(String top, String bottom);

    public void onAttach(Activity activity) {
        try {
            activityCommander = (TopSectionListener) activity;
        }catch(ClassCastException e){
            throw new ClassCastException(activity.toString());

at first bucky creates a reference of  TopSectionListener interface named  activityCommander.
but then he wrote this line of code that i don't understand:   activityCommander = (TopSectionListener) activity;
can someone explain this to me?

Post a Reply


Oldest  Newest  Rating
+2 Tim Herreijgers · January 20, 2015
Since activity Commander is a TopSectionListener variable and he wants to set it equal to a Activity variable he has to change the value of the Activity variable to a value of a TopSectionListener variable.

For example:
Button button = (Button) findViewById (R.id.button);

findViewById returns a View variable and button is a Button variable you have to read the View variable as a Button variable. Since Button extends TextView and TextView extends View you can read the View variable as a Button variable.
That's how much I understand of it. I hope it made some sense and it answered your question.
0 bobby habib · January 19, 2015
my exact question is why is he creating an object of an interface and then what is this:

activityCommander = (TopSectionListener) activity;
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator