1. private关键字
package test1;
public class Student {
//成员变量
private String name;
private int age;
//提供get/set方法
public void setName(String n){
name = n;
}
public String getName(){
return name;
}
public void setAge(int a){
age = a;
}
public int getAge(){
return age;
}
//成员方法
public void show() {
System.out.println(name + "," + age);
}
}
package test1;
public class StudentDemo {
public static void main(String[] args) {
//创建对象
Student s = new Student();
s.setName("林青霞");
s.setAge(30);
//使用成员方法
s.show();
}
}
2. this关键字
package test1;
public class Student {
// 成员变量
private String name;
private int age;
// 提供get/set方法
// public void setName(String n){
// name = n;
// }
public void setName(String name){
// name = name;
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
//成员方法
public void show() {
System.out.println(name + "," + age);
}
}
2.1 this内存原理
3. 封装
4. 构造方法
4.1 构造方法注意事项
4.2 标准类制作
package test1;
public class Student {
//成员变量
private String name;
private int age;
//构造方法
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//成员方法
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void show() {
System.out.println(name + "," + age);
}
}
package test1;
public class StudentDemo {
public static void main(String[] args) {
//创建对象s1
Student s1 = new Student();
s1.setName("林青霞");
s1.setAge(30);
s1.show();
//创建对象s2
Student s2 = new Student("林青霞",30);
s2.show();
}
}