封装
如何封装
- 定义属性时,定义为私有的:
public class Student { private String name; private int age; }
- 我们使用get、set方法设置属性:
public class Student { private String name;public String getName() { return name; } public void setName(String name) { this.name = name; } }
封装的意义
- 提高程序的安全性,保护数据
- 隐藏代码的实现细节
- 统一接口 ---get、set
- 提高系统的可维护性
代码实现
对sutdent类属性封装
package com.kuangstudy.Demo02; public class Student { private String name; private int age; //可以使用 alt + insert快捷添加get\set方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if(age > 120|| age < 0){ this.age = 3; }else{ this.age = age; } } }
对其进行调用
package com.kuangstudy.Demo02; public class Application { public static void main(String[] args) { Student student = new Student(); student.setName("李浩"); System.out.println(student.getName()); student.setAge(121); System.out.println(student.getAge()); } }
标签:封装,String,age,private,详解,public,name From: https://www.cnblogs.com/dragonstudy/p/16811069.html