定义一个外部类Father,有成员变量name并赋一个初值。

1、内部类的使用:
(1)定义一个外部类Father,有成员变量name并赋一个初值。
(2)定义一个内部类Child,并定义一个getValue()方法,在方法中调用外部类Father的name变量。
(3)定义一个测试类,在测试类的main方法中创建Child对象,并调用getValue()方法

Father.java

package com.fs.test;

class Father{
    private String name ="tiedan";
    class Child{  //定义一个内部类
         public void getValue(){  //定义一个普通方法
            System.out.println(name); //调用name属性
        }
    }
    //在外部类中定义一个方法,该方法负责产生内部类对象并且调用getValue()方法.
    public void getValue(){
        Child in = new Child();
        in.getValue();
        }
}


Test.java

package com.fs.test;

public class Test{
    public static void main(String[] args) {
        Father Out = new Father();//外部类对象
        Out.getValue(); //外部类方法
    }
}

猜你喜欢

转载自www.cnblogs.com/ooo888ooo/p/11105181.html