封装
封装要点:属性私有,get/set
封装的意义:
- 提高程序的安全性,保护数据
- 隐藏代码的实现细节
- 统一接口
- 提高系统的可维护性
package oop.seal;
public class Student {
//属性私有
private String name;
private int id;
private char sex;
private int age;
//提供可以操作属性的方法
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
//设置年龄范围
if(age>120 || age<0){
System.out.println("error");
}else {this.age = age;}
}
}
package oop.seal;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年龄");
int input = scanner.nextInt();
s1.setName("qinjiang");
System.out.println(s1.getName());
s1.setAge(input);
System.out.println(s1.getAge());
}
}
标签:封装,int,void,public,age,sex,id
From: https://www.cnblogs.com/qt0312/p/16748017.html