java——在方法中定义内部类1:

2019年2月16日16:05:29 发表评论 964 views
/**
 * Created by xabcd on 2019/2/16.
 */
public class java_outer
{
    int score = 95;
    void inst()
    {
        class Inner
        {
            void display()
            {
                System.out.println("成绩:score="+score);
            }
        }
        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();
    }
}



结果:
成绩:score=95




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

 

发表评论

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