Question

I have a couple of questions from the following code snippet:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // creating LinearLayout
        LinearLayout linLayout = new LinearLayout(this); //****QUESTION 2*********
        // specifying vertical orientation
        linLayout.setOrientation(LinearLayout.VERTICAL);
        // creating LayoutParams  
        LayoutParams linLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); //*****QUESTION 1***
        // set LinearLayout as a root element of the screen 
        setContentView(linLayout, linLayoutParam);
    }
  1. The base class is ViewGroup.LayoutParams, that is LayoutParams is a nested class of ViewGroup. I had also read that it is a static nested class. So why don't we refer to it using the outer class' name and dot notation:

    ViewGroup.LayoutParams linLayoutParam = new ViewGroup.Layout(...);
    
  2. In the following statement, what object is "this"? In the Java programming language, the this keyword in a method refers to the current object, i.e. the object to which this method belongs. But we are not explicitly calling (using an object) the onCreate() here in Android.

    LinearLayout linLayout = new LinearLayout(this);
    
Was it helpful?

Solution

... So why don't we refer to it using the outer class' name and dot notation

You seem to be unaware of the static imports in Java language. Mostly I like the way you are suggesting, i.e. refer to the inner class using the outer class name and the dot like ViewGroup.LayoutParams, instead of having an static imports. But, in some cases, if you might have to do that too many times then it's just better to have a static import rather than repeating the class name. You will see this kind of cases a lot while using the unit-testing frameworks like JUnit, which comes with class with a lot of static methods.

... In the following statement, what object is "this"?

There in your method, by using the keyword - this, you are referring to the current instance of the class in which you have declared/defined the instance method (i.e. the method @Override public void onCreate(Bundle savedInstanceState)).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top