使用静态内部类提高封装性

Java中的嵌套类分为两种:静态内部类和内部类。静态内部类就是在内部类的申明中加上static的修饰符。

实例:

““

package com.company;

public class Person {

private String name;

private Home home;

public Person(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Home getHome() {

return home;

}

public void setHome(Home home) {

this.home = home;

}

/**

* 静态内部类的调用

*/

public static class Home {

private String address;

private String tel;

public Home(String address, String tel) {

this.address = address;

this.tel = tel;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}

}

}

““

主函数:

““

package com.company;

import java.util.Random;

public class Main {

public static void main(String[] args) {

Person p = new Person(“张飞”);

p.setHome(new Person.Home(“三国”,”11234551”));

System.out.println(p.getName());

System.out.println(p.getHome().getAddress());

System.out.println(p.getHome().getTel());

}

}

““


版权声明:本文为weixin_30224231原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_30224231/article/details/114611639