A method that hides the attributes and implementation details of an object and provides only public access
Key: Priavte: Is an access modifier that modifies member variables and methods, and modifies members that can only be accessed within the class.
Personal summary: In the future, when we encapsulate a class (entity class), we will first define its properties (private to modify), and then define its GET /set methods.
packageJava package _01;/* * Define a student class * attributes: name, age, gender * method: show () --> Print this student's attributes * */
public class Student {
private String name;
private int age;
private String sex;
// Provide a method to set the name
public void setName(String name1) {
name =name1;
}
// Provide a method to get the name
public String getName(a) {
return name;
}
public int getAge(a) {
return age;
}
public void setAge(int age1) {
age=age1;
}
public String getSex(a) {
return sex;
}
void setSex(String sex1) {
sex=sex1;
}
public void Show(a) {
System.out.println("Name:"+name+", age:+age+", gender:+sex); }}Copy the code
packageJava package _01;public class StudentDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student student = new Student();
student.setName("Zhang Guowei");
student.setAge(23);
student.setSex("Male");
String name =student.getName();
System.out.println(name);// Output: Zhang Guowei
student.Show();// Output: Name: Zhang Guowei, age: 23, gender: male}}Copy the code