java(三十一)【面向对象】匿名内部类

一:匿名内部类

内部类定义在局部时:

  1. 不可以被成员修饰符修饰
  2. 可以直接访问外部类中的成员,因为还持有外部类中的引用,但是不可以访问它所在的局部中的变量,只能访问被fanal修饰的局部变量

从内部类中访问局部变量,变量需要被声明为最终类型fanal

 1 class out{
 2     int x=5;
 3     void methon(){ 
 4         final int y=6;  //局部变量
 5         class outter  //局部内部类,不可以被成员修饰符修饰,比如static,private
 6         {        
 7             void function()
 8             {
 9                 System.out.println(y);
10             }
11         }
12         new outter().function();
13     }
14 }
15 public class niming {
16     public static void main(String[] args) {
17         // TODO Auto-generated method stub
18         new out().methon();
19     }
20 }
View Code

结果:6

匿名内部类:

  • 匿名内部类其实就是内部类的一个简写格式。
  • 定义匿名内部类的前提:内部类必须继承一个类或者实现接口。
  • 匿名内部类的格式:new 父类或者接口(){定义子类的内容}
  • 匿名内部类就是一个匿名子类对象。可以理解为带内容的对象。
  • 匿名内部类中定义的方法最好不要超过3个。
 1 abstract class absdemo{ //抽象类
 2     abstract void show();
 3 }
 4 class out{
 5     int x=999;
 6     public  void function() {
 7         new absdemo() { 
 8             void show() {
 9                 System.out.println(x);
10             }
11         }.show();
12     }
13 }
14 public class niming {
15     public static void main(String[] args) {
16         new out().function();
17     }
18 }
View Code

结果:999

注意:匿名对象只能对方法调用一次

 1 abstract class absdemo{
 2     abstract void show();
 3 }
 4 class out{
 5     int x=999;
 6     public  void function() {
 7         new absdemo() {
 8             void show() {  //复写父类方法
 9                 System.out.println(x);
10             }
11             void show1() {    //子类特有方法
12                 System.out.println("haha");
13             }
14         }.show1();  //不能同时调用show方法与show1方法
15     }
16 }
17 public class niming {
18     public static void main(String[] args) {
19         new out().function();
20     }
21 }
View Code

结果:haha

实例一:补全代码

 1 import java.lang.reflect.Method;
 2 
 3 interface inter{
 4     void method();
 5 }
 6 /*
 7  内部类
 8  class test
 9  {
10     static class inner implements inter
11     {
12         public void method()
13         {
14             System.out.println("hah");
15         }
16     }
17     static    inter function()
18     {
19         return new inner();
20     }
21 }*/
22 //匿名内部类
23 class test
24 {
25     static inter function1()
26     {
27         return new inter()
28         {
29             public void method() 
30             {
31                 // TODO Auto-generated method stub
32                 System.out.println("hah");
33             }
34         };
35     }
36 }
37 public class innertest {
38     public static void main(String[] args) {
39     test.function1().method();
40     }
41 }
View Code

思路解析:

test.function1():test类中有一个静态的方法function1

.method();function这个方法运算后的结果是一个对象,而且是一个inter类型的对象。

 

posted @ 2016-06-02 16:28  花花妹子。  阅读(121)  评论(0)    收藏  举报