Java 内部类

1:定义一个接口

public interface ImyInterface {
    int get();
}

2:定义一个具体类,实现接口

class Implment1 implements ImyInterface{
    public int get() {
        return 23;
    }
    
    public String getStr(){
        return "hello World!";
    }
}

3:客户端调用

 ImyInterface interf = new Implment1();
 Implment1 instance = (Implment1)interf;  //用户可以将接口引用强转换回具体类引用,
 System.out.println(instance.getStr());   //进而,可以调用具体类中非接口方法

4:使用内部类

class Implment2{        
    private class inner implements ImyInterface{
        public int get(){
            return 666;
        }        
    }    
    
    public static ImyInterface getInterf(){        
        return instance.new inner();
    }    
        
    private Implment2(){}
    public static Implment2 instance = new Implment2();
}

5:用户调用

ImyInterface interf = Implment2.getInterf();
System.out.println(interf.get());

 小结:java内部类存在的必要性,其一就是避免用户不当地使用接口,如以上代码。

posted on 2013-03-28 14:43  邢同举  阅读(168)  评论(0)    收藏  举报

导航