1

I've been looking at the Android development tutorials and after looking through some code, I've noticed the following:

HeadlinesFragment mHeadlinesFragment; mHeadlinesFragment = (HeadlinesFragment) getSupportFragmentManager().findFragmentById( R.id.headlines); 

I am fairly new to Java so that may be the issue, but why is this explicit casting of (HeadlinesFragment) necessary? Is mHeadlinesFragment not already of type HeadlinesFragment?

Thanks!

1 Answer 1

3
getSupportFragmentManager().findFragmentById( R.id.headlines); 

this returns a Fragment Object, and HeadlinesFragment is sub class, of Fragment class, and everytime you assign an object of superclass to a reference of subclass you need to cast explicitly.

You dont need explicit casting when you are assigning a subclass object to super class reference, like assigning:

List<String> list=new ArrayList<String>(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, well said. The same can be said for just about anything else returned in Android really. The most popular being TextView view = (TextView)findViewById(R.id.some_text); What jeet is saying makes sense, because, if you think about it, its a lot easier to return a View, rather than think of some way to always know what a user will need returned, which you can't do`. So you make the programmer explicitly cast it saying, "I know what I'm doing."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.