黑马程序员技术交流社区

标题: 为什么内部类名前加final [打印本页]

作者: 旭辉lin    时间: 2014-8-28 09:52
标题: 为什么内部类名前加final
本帖最后由 旭辉lin 于 2014-8-30 21:07 编辑
  1. public class Test {

  2.         class Inner{
  3.                 public void show(){
  4.                         System.out.println("这是show()方法");
  5.                 };
  6.         }
  7.         public static void main(String[] args) {
  8.                 Test t=new Test();
  9.                 final Inner inner = t.new Inner();//这儿为什么必须是final?
  10.                 Thread thread=new Thread(){
  11.                         public void run() {inner.show();};
  12.                 };
  13.                 thread.start();
  14.         }

  15. }
复制代码

作者: lhtwm1    时间: 2014-8-28 11:37
final  最终的意思,呗修饰的成员,不能被复写,避免被继承。 昨天晚上刚看到这,不知道这么说能不能帮到你。
作者: 旭辉lin    时间: 2014-8-28 11:46
lhtwm1 发表于 2014-8-28 11:37
final  最终的意思,呗修饰的成员,不能被复写,避免被继承。 昨天晚上刚看到这,不知道这么说能不能帮到你 ...

能不能举个形象点的例子
作者: lhtwm1    时间: 2014-8-28 11:47
旭辉lin 发表于 2014-8-28 11:46
能不能举个形象点的例子

真对不起兄弟 我刚看到 final这集的视频。后面还没看。
作者: 旭辉lin    时间: 2014-8-28 12:19
  1. public class Test1 {
  2.         class InnerBBB {
  3.                 int b=100;
  4.         }

  5.         public static void main(String[] args) {
  6.                 Test1 test1 = new Test1();
  7.                 AAA innerAAA = test1.method();//如果innerBBB不声明为final,方法执行完innerBBB出栈,就无法访问成员变量b的值
  8.                 innerAAA.run();
  9.         }

  10.         public AAA method() {
  11.                 final InnerBBB innerBBB = new InnerBBB();//声明为final
  12.                 class InnerAAA implements AAA {
  13.                         @Override
  14.                         public void run() {
  15.                                 System.out.println("访问内部类InnerBBB的成员变量b的值是"+innerBBB.b);
  16.                         }
  17.                 }
  18.                 InnerAAA innerAAA = new InnerAAA();
  19.                 // innerAAA.run();
  20.                 return innerAAA;

  21.         }
  22. }

  23. interface AAA {
  24.         void run();
  25. }
复制代码

作者: 旭辉lin    时间: 2014-8-28 12:21
自己想出来的,希望可以帮助到大家。




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