封装
package com.oop.demo04;
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("请");
System.out.println(s1.gerName());
s1.setAge(999);
System.out.println(s1.getSex());
}
}
package com.oop.demo04;
public class Student {
//属性私有
private String name;//名字
private int id;//学号
private char sex;//性别
private int age;//年龄
//提供一些可以操控这个属性的方法!
//提供一些public的get,set方法
//get 获得这个数据
public String gerName(){
return this.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;
}
//set给这个数值赋值
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 = age;
}else{
age=3;
}
}
}

浙公网安备 33010602011771号