java面向对象——定义2个类,并进行测试

定义一个Father和Child类,Father为外部类,类中定义一个私有的String类型的属性name;Child为Father的内部类,其中定义一个introFather()方法,方法中调用Father类的name属性;再定义一个测试类,在类的main方法中创建Child对象,并调用introFather()方法。

class Father{
    private String name="lidazhuang";
    class Child{
        public void introFather(){
            System.out.println(name);
        }
    }
}
public class Test {
    public static void main(String[] args) {
           Father.Child child=new Father().new Child();
           child.introFather();
    }
}

运行结果:
在这里插入图片描述
内部类与外部类可以访问彼此的私有属性(内部类直接访问,外部类通过内部类对象访问)

在外部类的外部创建成员内部类对象语法:
外部类.内部类 内部类名称=new 外部类().new 内部类();
例如:

 Father.Child child=new Father().new Child();

猜你喜欢

转载自blog.csdn.net/qq_44149554/article/details/88578370