java 匿名内部类


/*
内部类定义在局部 
01 不可以被成员修饰符修饰
02 可以直接访问外部类的成员 因为还持有外部类的引用
    但是不可以访问他所在的局部中的变量 只能访问被fianl修饰的局部变量 


class Outer
{
int x=3;
void show(final int a)
{      
  final int y=123;
  class Inter
  {
  void funtion()
           {
   // 可以直接访问外部类的成员 因为还持有外部类的引用
   System.out.println(Outer.this.x);
  // 无法访问  但是加上final就可以访问
System.out.println(y);
System.out.println(a);
  }
  }
  //这个是匿名对象 通过匿名对象访问内部类 
  new Inter().funtion();
}
}
class    Inter
{
public static void main(String[] args) 
{
//new Outer().show();
Outer out=new Outer();
//  out.show(7);
 out.show(90);
}
}
*/
/* 
 匿名内部类     
1 就是内部类的简写格式
 2   定义匿名内部类的前提是 内部类必须继承一个类 或者是实现一个接口
  3 内部类可以继承外部其他抽象类  和接口
  4 匿名内部类 格式 new 父类或者接口(){定义的子类内容}
  5 匿名内部类是一个匿名子类对象
  6 匿名内部类中的方法最好不要超过3个
*/




abstract  class  Demo
{
abstract void method();
}
class Outer
{
//int x=22;
/*class Inter extends   Demo
{
//int x=12121;
void method()
{
//System.out.println(Outer.this.x);
    System.out.println(x);
}
}
 
*/
   public  void funtion()
{
      /*
 //匿名内部类
        new Demo()
  {
   void  method()
{
 System.out.println("#23");
}
void show()
  {
System.out.println("21");
}
  }.show();
   new Demo()
  {
   void  method()
{
 System.out.println("#23");
}
void show()
  {
System.out.println("21");
}
  }.method();


       Demo d=new Demo()
{
    void method()
{
  System.out.println("1");
}
void  show()
{
  System.out.println("12314");
}
};
d.show();
d.method();
  */




    Demo dd=new Demo()
  {
void show()
  {
System.out.println("21");
}
   void  method()
{
 System.out.println("#23");
}
  };
   
  dd.method();
  // 编译失败  
//  dd.show();
  
}
}
class  Inter
{
public static void main(String[] args) 
{
//Outer out=new Outer();
//out.funtion();
new Outer().funtion();
}
}










//匿名内部类


interface  Inter
{
   void show();
}
class  Demo
{   

/* 01 定义一个静态内部类 
static class Imnter1  implements Inter
{
public void show()
{
System.out.println("12");
}
}
// 用于访问内部类
static Imnter1 funtion()
{
 return new Imnter1();
}


  //02 用匿名对象访问 内部类 
static  Inter funtion()
{
   return  new  Inter
}


*/


}
 
class  Innter
{
public static void main(String[] args) 
{
// Demo.funtion().show();

   show(new Inter()
{
     public void show()
{
  System.out.println("121");
}
   });
}
public   static void show(Inter in)
{
 in.show();
}
}










//面试题   匿名内部类    内部类必须是继承一个类或者是实现一个接口
class  Inntertest
{
public static void main(String[] arg)
{
 new Object()
{
   public void funtion()
{

}
 }.funtion();
}
}






详细请查看:<a href="http://edu.csdn.net" target="blank">http://edu.csdn.net</a>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值