java——方法中的内部类2:final

2019年2月16日16:13:44 发表评论 921 views

在 方法 中 定义 的 内部 类 只能 访问 方法 中的 final 类型 的 局部 变量, 因为 用 final 定义 的 局部 变量 相当于 一个 常量, 它的 生命 周期 超出 方法 运行 的 生命 周期, 如下 面的 范例

/**
 * Created by xabcd on 2019/2/16.
 */
public class java_outer
{
    int score = 95;
    void inst(final int s)
    {
         final int temp = 20;//此处若不加final则会出错
        class Inner
        {
            void display()
            {
                System.out.println("成绩:score="+(score+s+temp));
            }
        }
        Inner in = new Inner();
        in.display();

    }
}



/**
 * Created by xabcd on 2019/2/16.
 */
public class test_outer
{
    public static void main(String[] args)
    {
        java_outer ou = new java_outer();

        ou.inst(5);
    }
}



结果:
成绩:score=120

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: