Friday, December 6, 2013

java inner class

1. Inner class are helper classes that can access member variables of  something outer (class, function, blocks and expression ) and are for local use only. They are no need to be aware of by outside world. 

2. Three types of inner classes:
inner class: inside a class
local class: inside any block ( expression, statement or block )
anonymous class: are expressions

Not matter how you categorize them, basically they are local to something outer.

I want to talk a little more about anonymous class. Basically it's 2-in-1: implementation + initialization

    interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);
    }

    HelloWorld frenchGreeting = new HelloWorld() {
        String name = "tout le monde";
        public void greet() {
            greetSomeone("tout le monde");
        }
        public void greetSomeone(String someone) {
           name = someone;
           System.out.println("Salut " + name);
        }
    };
 
It's the same as 
 class FrenchGreeting implements HelloWorld { same blah above...}
 FrenchGreeting frenchGreeting = new FrenchGreeting();
 
However, by doing 2-in-1, you not only get rid of creating 
new class name FrenchGreeting, which is why it's called anonymous 
class,  but also initialize an object of it. So it's much simpler. 

No comments:

Post a Comment