public class Test {
    public static void main(String[] args) {
        Outer  o = new Outer();
        o.getInnerFuntion();
    }
}
class Outer {
     int x = 0 ;
    private class Inner{            
        void function(){
            System.out.println("x="+x);
        }
    } 
    public void getInnerFuntion(){
        new Inner().function();;
    }
}2.思考方式如下
a匿名内部类就是没有名字的内部类
b那么如何new对象inner呢?
那么此内部类需要继承父类或者实现接口
public class Test {
    public static void main(String[] args) {
    Outer  o = new Outer();
        o.getInnerFuntion();
    }
}
//内部类要实现的接口
interface Demo{
    void function();
}
class Outer {
     int x = 0 ;
    private class Inner{            
            void function(){
                System.out.println("x="+x);
            }
    } 
    public void getInnerFuntion(){
        new Inner().function();;
    }
}上述程序把内部类中的funciton()方法提取成了一个接口
public class Test {
    public static void main(String[] args) {
        Outer  o = new Outer();
        o.getInnerFuntion();
    }
}
interface Demo{
    void function();
}
class Outer {
     int x = 0 ;
    public void getInnerFuntion(){
        new Demo() {
            @Override
            public void function() {
                System.out.println("x="+x);
            }
        }.function();//调用内部类中的方法
    }
}上述程序已经是个局部内部类了,我们发现局部内部类有个缺点,那就是只能调用一个方法,如果想调用多个方法,那么就需要多次的尽兴new对象,所以我们思考能不能给匿名内部类取名字呐?能
但是要注意用名字访问只能访问访问内部已有的方法,因为多态
匿名内部类中的方法最多不要超过3个(不包含3个),因为阅读性差
没有父类没有接口,能写匿名内部类吗?能 new Object()
public class Test {
    public static void main(String[] args) {
        Outer  o = new Outer();
        o.getInnerFuntion();
    }
}
class Outer {
     int x = 0 ;
    public void getInnerFuntion(){
        Object demo = new Object() {
            public void function() {
                System.out.println("x="+x);
            }
            @Override
            public String toString() {
                return super.toString();
            }
        };
        //The method function() is undefined for the type Object
        demo.function();
        demo.toString();
    }
}练习题
public class Demo {
    public static void main(String[] args) {
        Test.function().method();
    }
}
interface Inter{
    void method();
}
class Test {
    //用内部类在此处填写代码
}/答案:
static Inter function(){
Inter in =  new Inter(){
public void method(){
System.out.println("method");
}
};
return in;
}/
原文:http://blog.51cto.com/13579086/2066271