Class encapsulation private

     Class encapsulation

  1. Java mainly controls whether the members (variables, methods) in the class can be accessed through the private and public access modifiers;
  2. Public means public, and the member variables and member methods it modifies can be accessed (called) by any other classes and programs;
  3. Private means private, and the member variables and member methods it modifies can not be accessed and called by other classes and programs except for its own methods in this class;

      How to access the member variables of the encapsulated chess class?

  1. A member variable method can be used to set (modify) the value of a private member variable. Such a method name usually contains "set()", so it is usually called a setter method.
  2. When reading the value of a private member variable, a member method is used. Such a method usually contains "get", so it is usually called a "getter()" method

      Student category: Student

package mine;

public class Student {
	private String name;
	private String sex;
	private int age;
	private float score;
	//无参构造
	Student() {
		name="";
		sex="";
		age=0;
		score=0.0f;
	}
	//有参构造
	Student(String inNAme,String inSex, int inAge ,float inScore){
		setAge(inAge);
		setName(inNAme);
		setScore(inScore);
		setSex(inSex);
		
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", sex=" + sex + ", age=" + age + ", score=" + score + "]";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	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;
	}
	
	public void speak() {
		if (name.equals("")) {
			System.out.println("该生没有姓名,暂时无法介绍");
			
		}else 
			System.out.print("自我介绍:我叫"+name+","+sex+"今年"+age+"岁,");
		
	}
	public void grade() {
			if (score<=0.0f) {
				System.out.println("暂时没有该学生信息");
			} else {
				System.out.println("java考试得分"+score);
			}
	}
	
}

 

Main function: StudentTest test class

package mine;

public class StudentTest {
	public static void main(String[] args) {
		Student stu1 =new Student();
	
		stu1.setName("xl");
		stu1.setSex("男");
		stu1.setAge(22);
		stu1.setScore(100);
		stu1.speak();
		stu1.grade();
		
		
		Student stu2 =new Student("qq","女",22,100.0f);
		stu2.speak();
		stu2.grade();
		
	}
}

 

Guess you like

Origin blog.csdn.net/LL__Sunny/article/details/108533027