首页 > 其他 > 详细

匿名内部类

时间:2016-02-29 21:31:30      阅读:112      评论:0      收藏:0      [点我收藏+]

匿名内部类适合用于创建只是用一次的类

1.通过实现接口创建的匿名内部类,例:

1 package Class_study;
2 
3 public interface Product {//接口
4     public int getPrice();
5     public int getWeight();
6 
7 }
 1 package Class_study;
 2 
 3 public class TestProduct {
 4     public void test(Product p){
 5         System.out.println(p.getPrice()+"     "+p.getWeight());//使用
 6     }
 7     public static void main(String args[]){
 8         TestProduct ta=new TestProduct();
 9         ta.test(new Product(){//匿名内部类定义部分
10             public int getPrice(){
11                 return 6;
12             }
13             public int getWeight(){
14                 return 5;
15             }
16         });
17     }
18 
19 }

2.继承父类或者抽象类,构造匿名内部类,可以传入参数,即继承父类的构造函数

1 public abstract class Dog {//抽象类
2     public String name;
3     public abstract void run();
4     public Dog(){};
5     public Dog(String name){
6         this.name=name;
7     }
8 
9 }

 

package Class_study;

public class Test_Dog {
    public void test(Dog d){
        System.out.println(""+d.name);
        d.run();
    }
    public static void main(String args[]){
        new Test_Dog().test(new Dog("Tom"){//含参数的匿名内部类,继承父类或抽象类的构造函数
            public void run(){
                System.out.println("这只狗正在跑");
            }
        });
    }
}

 3.如果匿名内部类要访问外部类属性,属性必须使用final修饰

 1 package Class_study;
 2 
 3 public class Test_Dog {
 4     private  final int Max=20;//用final修饰后 ,匿名内部类才能访问
 5     private  int Max_2=9;
 6     public void test(Dog d){
 7         System.out.println(""+d.name);
 8         d.run();
 9     }
10     public static void main(String args[]){
11         new Test_Dog().test(new Dog("Tom"){//含参数的匿名内部类,继承父类或抽象类的构造函数
12             public void run(){
13                 System.out.println("这只狗正在跑"+"时速"+new Test_Dog().Max+"m/s");//访问使用final修饰的属性
14                 System.out.println(new Test_Dog().Max_2);//书上说放在内部类里必须用final修饰  但是放在内部类的方法里可以不用final修饰
15                 
16             }
17             //System.out.println(new Test_Dog().Max_2);//不放在方法里使用会出现编译错误
18         });
19     }
20 }

 

匿名内部类

原文:http://www.cnblogs.com/abstract-fabulous/p/5228750.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!