package day04;
/*
封裝:屬性設(shè)置為private的,封裝在類的內(nèi)部,對(duì)外提供public的get/set方法供外部調(diào)用。
在類內(nèi)部對(duì)參數(shù)做一些限制,防止非法的調(diào)用。
*/
public class Demo01 {
public static void main(String[] args) {
Student s1 = new Student("zhangsan", 18, 90);
System.out.println(s1);
// 在類的外部可以訪問到屬性。
s1.name = "張三"; // 設(shè)置/獲取屬性,實(shí)例。屬性名。
s1.score = 99; // 0~150
System.out.println(s1);
// 設(shè)置的分?jǐn)?shù)不合理,也能設(shè)置
s1.score = -500;
System.out.println(s1);
Student1 s2 = new Student1("lisi", 18, 90);
System.out.println(s2);
// s2.name = "李四"; // 私有的屬性在外部無(wú)法訪問
// 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("參數(shù)錯(cuò)誤");
} else {
age = a;
}
}
// 獲取屬性的值
public float getScore() {
return score;
}
// 設(shè)置屬性的值
public void setScore(float s) {
if (s < 0 || s > 150) {
System.out.println("參數(shù)不合法");
} 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;
}
}
|