Solved

Casting in Java, why?

Posted on 2013-05-19
3
404 Views
Last Modified: 2013-05-20
Hello Experts,

This is what I expect to be a 'noob' question, but I cannot figure out why I need to Cast this object.  I have a button in my Android app and apparently have to Cast the object...why?  Code below:
Button b = (Button) findViewById(R.id.button1);

Open in new window

FYI...I'm following a tutorial on Lynda.com and this was mentioned as important.  I would really appreciate any help to understand 'why' it needs to be Cast as a button when it IS a button already and b was type cast as a button too.

Thank you.
0
Comment
Question by:Modifier1000
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 26

Expert Comment

by:ksivananth
ID: 39180229
though the actual view is a button, the return type of findViewById is different than Button.
0
 
LVL 7

Accepted Solution

by:
Beneford earned 500 total points
ID: 39180235
findViewById() is actually returning a View object (a Button is a subclass of TextView which is a subclass of View)
You know that the View returned is a Button, but the Java sysem can't work that out just by looking at the source code. The type check system tries to stop you doing things that aren't going to work (very useful most of the time), and the cast is how you tell the type check system that you really do know what's going on.
0
 

Author Closing Comment

by:Modifier1000
ID: 39181111
Thank you for the explanation, very helpful in giving more depth to your answer.
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, people trade privacy and security for convenience. However in today's concrete jungle, this is an extremely foolish decision considering the vast amount of technologies being used against consumer interest. First off, I won't waste any time e…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question