zoukankan      html  css  js  c++  java
  • 内部类访问外部同名属性或者方法

      如果内部类中没有与外部类同名的属性或方法,那么直接引用外部类的属性或方法即可,见Inner类的定义。
        但如果存在同名的属性或方法,就要在内部类中先取得外部类的引用,通过这个引用来访问外部类的同名属性或方法。有两个方法来取得外部类的引用:
        一种方法是,通过外部类的类名来取得外部类当前的引用,见Inner1类的定义;
        另一种方法是,把外部类的引用显式传给内部类的构造方法,见Inner2类的定义。
        可见,第一种方法简单一些。
        注意:[类名.this]的用法只能在内部类中使用。
    public class Test1 {

        private int a = 5;

        public Test1() {

            new Inner().print();
            new Inner1().print();
            new Inner2(this).print();

        }

        public static void main(String[] args) {

            new Test1();
        }

        private class Inner {

            private void print() {

                System.out.println("Inner直接取得外部的属性a=" + a);
                System.out.println();

            }

        }

        private class Inner1 {

            private int a = 10;

            private void print() {

                System.out.println("Inner1的属性a=" + this.a);
                System.out.println("Inner1通过第一种方法取得外部的属性a=" + Test1.this.a);
                System.out.println();

            }

        }

        private class Inner2 {

            private int a = 20;

            private Test1 t;

            private Inner2(Test1 t) {
                this.t = t;
            }

            private void print() {

                System.out.println("Inner2的属性a=" + this.a);
                System.out.println("Inner2通过第二种方法取得外部的属性a=" + this.t.a);
                System.out.println();

            }

        }

    }

  • 相关阅读:
    Spring面试,IoC和AOP的理解
    WEB打印(jsp版)
    Spring事务管理机制的实现原理-动态代理
    spring面试题
    oracle PLSQL基础学习
    oracle创建表空间
    WM_CONCAT字符超过4000的处理办法
    Oracle 数据泵使用详解
    Oracle 数据泵详解
    linux下启动oracle
  • 原文地址:https://www.cnblogs.com/tina-smile/p/3599396.html
Copyright © 2011-2022 走看看