Solved

Casting in Java, why?

Posted on 2013-05-19
3
402 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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

A short article about problems I had with the new location API and permissions in Marshmallow
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
This video is in connection to the article "The case of a missing mobile phone (https://www.experts-exchange.com/articles/28474/The-Case-of-a-Missing-Mobile-Phone.html)". It will help one to understand clearly the steps to track a lost android phone.

730 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