- class Test_InnerClassAnonymousClass {
- public static void main(String[] args) {
- Animal.Cat ac=new Animal().new Cat();//内部类需要创建对象才可以调用;
- ac.print();
-
- Animal a=new Animal();//局部内部类需要调用类所在的方法;
- a.method();
- }
- }
- interface Inter{
- public void method();
- }
- class Animal{
- private int num=20;
- class Cat{
- int num=10;
- public void print(){
- System.out.println(this.num);
- System.out.println(Animal.this.num); //内部类调用外部类成员变量;
- Dog d=new Dog(); //内部类的之间的相互调用,和类与类之间调用是一样的;
- d.print();
- }
- }
- class Dog{
- int num=30;
- public void print(){
- System.out.println(this.num);
- }
- }
- public void method(){
- int num=40;
- class Mouse { //局部内部类;
- final int num=50;
- public void print(){
- System.out.println(this.num);
- }
- }
- Mouse m=new Mouse(); //局部内部类只能在方法内部创建对象调用;
- m.print();
- new Inter(){ //匿名内部类要继承一个类或者接口;
- public void method(){
- System.out.println("AnonymousInnerClass");
- }
- };
- }
- }
-
复制代码 |
|