private修饰后,当前变量只能在当前的内中才能操作
// 定义一个学生类
class Student{
String name;
private int score;
public void setScore(int s){
if (s>=0 && s<=100){
score = s;
}else {
System.out.println("成绩不符合规范!");
}
}
public void show(){
System.out.println("姓名:"+name);
System.out.println("分数:"+score);
}
}
public class StudentDemo1 {
public static void main(String[] args) {
Student s1 = new Student();
//为S1对象的成员变量
s1.name = "张飞";
// s1.score = -30;
s1.setScore(90);
s1.show();
}
}
private 设置为私有属性
java中用this修饰的变量为成员变量
// 定义一个学生类
class Student{
String name;
private int score;
public void setScore(int score){
if (score>=0 && score<=100){
this.score = score;
System.out.println(this);
}else {
System.out.println("成绩不符合规范!");
}
}
public void show(){
System.out.println("姓名:"+name);
System.out.println("分数:"+score);
}
}
public class StudentDemo1 {
public static void main(String[] args) {
Student s1 = new Student();
//为S1对象的成员变量
s1.name = "张飞";
// s1.score = -30;
s1.setScore(90);
s1.show();
}
}
标签:java,int,修饰符,private,score,setScore
From: https://www.cnblogs.com/ch2020/p/16843903.html