Please help me clear this doubt I have in my head once and for all, considering the following two cases.
Case 1:
public class Activity {
WebView mWebview;
@Override
public void onCreate(Bundle savedInstanceState) {
initWebView();
}
public void initWebView() {
mWebView = (WebView) findViewById(R.id.webview);
}
}
- Does
findViewById()instantiate a
newWebViewobject the second time
it is called? - If the answer is ‘yes’, is the old
WebViewobject (that was previously
assigned tomWebView) automatically
destroyed? (i.e. gets lost by being
placed in a queue for garbage
collection)
Case 2:
public class Activity {
WebView mWebview;
MyPictureListener mPictureListener;
@Override
public void onCreate(Bundle savedInstanceState) {
initWebView();
}
public void initWebView() {
mWebView = (WebView) findViewById(R.id.webview);
mPictureListener = new MyPictureListener(mWebView);
mWebView.setPictureListener(mPictureListener);
}
}
- When
initWebView()is called a
second time, is the old
MyPictureListenerobject (that was
previously assigned to
mPictureListener) automatically
destroyed? (i.e. gets lost by being
placed in a queue for garbage
collection)
Case 1: No matter how many times you call
findViewById(R.id.webview), the object returned is the same WebView that was created when the layout was inflated by the UI framework. When you assign it to your variable, you’re just saying “I want a handle to that Object,” and that’s all it is. If you setmWebViewtonull, the Object still exists with references to it from the Activity’s UI, you just can’t access it frommWebViewanymore.Case 2: Yes (insofar as ‘automatically destroyed’ works in Java). Your
mWebViewhas a handle (a pointer) to aMyPictureListenerObject, when you assign it to a new instance of that class, the reference to the old Object is lost, and the old Object is now a candidate for garbage collection.This is really a [grossly generalized] mini-explanation of how pointers work, which is a concept I’ve heard some people say that Java doesn’t use. That’s completely erroneous, and getting comfortable with pointers as they are used in C++ will give you much better insight into these kinds of questions in the future.