Chinaunix首页 | 论坛 | 博客
  • 博客访问: 30392439
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2008-04-08 10:44:06

// 接口 注意对比 Runnable接口,

package innerclass.noname;

public interface Interf {
 public void run();

}
// 实现的子类 注意对比 Thread类


package innerclass.noname;

public class InterfImpl implements Interf{
 Interf target;
 public InterfImpl(Interf i){
  this.target=i;
 }

 public void run(){
  target.run();
 }
 
 public void startRun(){
  while(true){
   run();
  }
 }

}
// 测试类Test 仿照于:http://blog.sina.com.cn/s/blog_493035f601007u42.html


private static void startWriterThread() {
       new Thread(new Runnable() {
            public void run() {
                byte[] outArray = new byte[2000];
                while(true) { // 无终止条件的循环

                    try {
                        // 在该线程阻塞之前,有最多1024字节的数据被写入

                        pipedOS.write(outArray, 0, 2000);
                    }
                    catch(IOException e) {
                        System.err.println("写操作错误");
                        System.exit(1);
                    }
                    System.out.println(" 已经发送2000字节...");
                }
            }
        }).start();// 注意:内部类使用哦........

    } // startWriterThread()


 

那么测试类 Test1 如下:

package innerclass.noname;

public class Test {
 public void doSome(){
  new InterfImpl(new Interf(){
   public void run(){
    System.out.println("doSome");
   }
  }).startRun();
 }
 public static void main(String agr[]){
  new Test().doSome();
 }
}


// 测试类2 Test2


如下: 一是:用于返回 匿名内部类实现类Obj 但是接口类型哦,然后调用接口实现的方法,二是:直接调用......

 interface example {
    public void move();
 }
 class main{
 example a=new example(){
          x++; }
   }
new example(){} 产生了一个example 的匿名子类,并一同实现了他,类型并转向了它...

 

package innerclass.noname;

public class test2 {
 // 返回接口类型 obj;

// public Interf test(){

// return new Interf(){

// public void run(){

// System.out.println("+++++++++++++++");

// }

// };

// }

 public void test2(){
   new Interf(){
  public void run(){
   System.out.println("+++++++++++++++");
   }
  }.run();
 }
 public static void main(String agr[]){
  new test2().test2();
  // new Test2().test().run();

 }
}

// 带参匿名内部类


 例子:参照:http://blog.sina.com.cn/s/blog_493035f601000ajb.html


如果这个匿名内部类继承了一个只含有带参数构造函数的父类,创建它的时候必须带上这些参数,并在实现的过程中使用super关键字调用相应的内容)

 

// 超类 带参构造函数


package innerclass.noname;

public class SuperClass {
 int age;
 public SuperClass(int age){
  this.age=age;
 }
 //实现类



package innerclass.noname;

public class InnerClass extends SuperClass {

 public InnerClass(int age) {
  super(age);
 }

}


// 测试类


package innerclass.noname;

public class TestInnerClass {
 int age=21;
 String name="李强";//不是final类型

blic void print(){
  new InnerClass(age){
  }.printAge(name);
 }
 public static void main(String agr[]){
  new TestInnerClass().print();
 }
}

输出:李强 ‘age is 21



阅读(1547) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~