package day04;
/*
封装:属性设置为private的,封装在类的内部,对外提供public的get/set方法供外部调用。
在类内部对参数做一些限制,防止非法的调用。
*/
public class Demo01 {
public static void main(String[] args) {
Student s1 = new Student("zhangsan", 18, 90);
System.out.println(s1);
// 在类的外部可以访问到属性。
s1.name = "张三"; // 设置/获取属性,实例。属性名。
s1.score = 99; // 0~150
System.out.println(s1);
// 设置的分数不合理,也能设置
s1.score = -500;
System.out.println(s1);
Student1 s2 = new Student1("lisi", 18, 90);
System.out.println(s2);
// s2.name = "李四"; // 私有的属性在外部无法访问
// s2.score = 99;
s2.setScore(100);
System.out.println(s2.getScore());
s2.setAge(30);
System.out.println(s2.getAge());
}
}
// 未封装的
class Student {
String name;
int age;
float score;
public Student(String name, int age, float score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
// 封装后的
class Student1 {
private String name;
private int age; // 3~30
private float score;
public int getAge() {
return age;
}
public void setAge(int a) {
if (a<3 || a>30) {
System.out.println("参数错误");
} else {
age = a;
}
}
// 获取属性的值
public float getScore() {
return score;
}
// 设置属性的值
public void setScore(float s) {
if (s < 0 || s > 150) {
System.out.println("参数不合法");
} else {
score = s;
}
}
public Student1(String name, int age, float score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student1{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
class Student2 {
private String name;
private int age;
private float score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
}
|