黑马程序员技术交流社区

标题: 匿名对象可以这么玩—无限循环调用 [打印本页]

作者: as604049322    时间: 2014-12-17 10:12
标题: 匿名对象可以这么玩—无限循环调用
下面一点简单的代码几乎包涵面向对象70%的知识哦。
  1. class Extends
  2. {
  3.     public static void main(String[] args)
  4.     {
  5.         new Runner(){
  6.             public void getSum(int a,int b){
  7.                 System.out.println(a+b);
  8.             }
  9.         }.getSum(2,3);
  10.         new Pelope(){
  11.             public Pelope shot(){
  12.                 System.out.println("喊一声");
  13.                 return this;
  14.             }
  15.         }.shot().getSum(1,3);
  16.         
  17.         new SuperPelope().shot().shot().shot().shot()
  18.             .shot().shot().shot().shot().shot().shot()
  19.             .shot().shot().shot().shot().shot().getSum(SuperPelope.count,0);
  20.         //可以一直喊下去。
  21.         //也可以通过for循环控制喊叫次数。。。
  22.         SuperPelope.count=0;
  23.         SuperPelope pe=new SuperPelope();
  24.         for(int i=0;i<20;i++){
  25.             pe=(SuperPelope)pe.shot();
  26.         }
  27.     }
  28. }

  29. interface Runner
  30. {
  31.     void getSum(int a,int b);
  32. }

  33. abstract class Pelope implements Runner{
  34.     public void getSum(int a,int b){
  35.         System.out.println(a+b);
  36.     }
  37.     abstract Pelope shot();
  38. }

  39. class SuperPelope extends Pelope
  40. {
  41.     static int count=0;
  42.     public Pelope shot(){
  43.         System.out.println("喊"+(++count)+"声!");
  44.         return this;
  45.     }
  46. }
复制代码

作者: 我只是一只菜鸟    时间: 2014-12-17 10:22
是匿名内部类吧?
作者: as604049322    时间: 2014-12-17 12:08
我只是一只菜鸟 发表于 2014-12-17 10:22
是匿名内部类吧?

额。。我的用词不专业




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2