简体   繁体   中英

What does new Foo(bar) {public void baz(){…} }; mean in Java?

I'm trying to understand the NavigationDrawer sample for the Android SDK and I met this:

 ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description for accessibility */
            R.string.drawer_close  /* "close drawer" description for accessibility */
            ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

When do these methods get called, right after the instantiation? I'm not familiar with this syntax. How does this work? Thanks

This is an anonymous inner class. Given an interface or class Foo with 0 or more abstract methods, you can use:

Foo blech=new Foo(){
    void bar(int baz){
        System.out.println("quux");
    }
}

to create an instance of Foo with methods implemented or overridden. All abstract methods(of which there may be 0) will need to be implemented in the braces. The constructor is still called as usual and parameters can be passed in the parentheses.

These are often used for listeners or other objects that need to be run and should specify different actions without creating new classes extending or implementing them.

These will compile down to [Outer Class]$[Number].class , once for each anonymous inner class used in the code, even if any are never reached or any are used multiple times

It is possible to override methods of a class for one specific instance by using that syntax. A very common usage is indeed Listeners or Handlers (eg: MouseListener, KeyListener, etc...).

This results in an anonymous subclass of the class you are extending. The subclass has no name. And is compiled into WrapperClass$0 , WrapperClass$1 and so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM