Search code examples
javaandroidinner-classesnested-class

Android & Java inner class concept


i followed the link http://developer.android.com/reference/android/app/AlertDialog.html and i try to create new AlertDialog like this

AlertDialog myAlertDialog = new AlertDialog.Builder(MainActivity.this).create();

as per the document AlerDialog is the outerclass and Builder is the inner class within AlertDialog. Now i linked the same concept with java in accessing the inner class like this Outer myOuter2 = new Outer.Inner(); this piece of gives error when i try to access, here is the complete java code

package com.test;

    public class Outer {
        public void OuterMethod() {
            System.out.println("OuterMethod");
        }

        public static void main(String[] args) {
            Outer myOuter = new Outer();

            myOuter.OuterMethod();
            Outer myOuter2 = new Outer.Inner();//this piece of code gives error

        }

        class Inner {

            Inner() {
                System.out.println("constructor Inner");
            }

            public void InnerMethod() {
                System.out.println("Inside InnerMethod");
            }
        }
    }

so my question over here is how to understand the same inner class concept in android and accessing the methods within that


Solution

  • You have created an inner non-static class (an inner instance class), whereas AlertDialog.Builder is a static class.

    To get your code to work as is you need an interesting way of invoking new that goes like this:

    Outer.Inner myOuter2 = myOuter.new Inner();
    

    This is because it acts much like any other non-static field within Outer - it requires an instance of Outer in order to be valid. In any event, this is often not a good idea as public inner non-static classes are rare.

    More likely you want Inner to be a static class, i.e. one declared as:

    static class Inner {
    

    Essentially this decouples Inner from its containing class, it just happens to live inside it and so can be instantiated via new Outer.Inner(). It could happily live as a public class in its own right in a new .java file instead.

    Inner static classes are useful when the inner class is only used in relation the outer class, so it shows the relationship between them.

    In Android's case you use an AlertDialog.Builder only when building an AlertDialog. If it was a general Builder used by other classes (e.g. a plain Dialog) is would have instead been declared as its own public class (i.e. a standalone class that is not nested inside another).