day06-封装的优化_this的概述和使用

This commit is contained in:
2026-07-19 14:46:54 +08:00
parent 185d689b94
commit 8476e4095e
2 changed files with 31 additions and 14 deletions
@@ -15,10 +15,15 @@ public class Demo03 {
//s.age = -18;
//s.id = 2;
//针对私有化的属性进行取值赋值
//赋值
s.setAge(18);
System.out.println("对象s的地址:"+s);
s.setName("张三");
s.setId(2);
s.study("SQL");
//取值
int id = s.getId();
int age = s.getAge();
}
}
+26 -14
View File
@@ -5,42 +5,54 @@ public class Student {
private int age;
private int id;
//获取年龄
public int getAge(){
return age;
}
//设置年龄
public void setAge(int a){
if (a >= 0 && a <= 120) {
age = a;
public void setAge(int age){
if (age >= 0 && age <= 120) {
this.age = age;
} else {
System.out.println("年龄不合法,请输入0~120的年龄");
}
}
//获取年龄
public int getAge(){
return this.age;
}
public int getId(){
return id;
return this.id;
}
//设置年龄
public void setId(int b){
id = b;
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
return this.name;
}
//设置年龄
public void setName(String n){
name = n;
public void setName(String name){//shfit+F6:重命名
/*
name = name;
当前代码想要的效果:成员变量 = 局部变量
但当前的效果:局部变量 = 局部变量
如何解决当前重名的问题???
使用this:this.成员变量名,一定表示当前对象的成员变量
this:表示一个对象,哪个对象调用了当前的方法,那么这个this就表示该对象
总结:在一个描述类中,所有的成员变量和成员方法,前面都有this.,哪怕你不写,编译器也会主动加上!!!!!
*/
System.out.println("setName方法中的this:"+this);
this.name = name;
}
//学习
public void study(String book){
System.out.println("姓名为"+name+""+age+"岁的学生正在学习"+book);
System.out.println("姓名为"+this.name+""+this.age+"岁的学生正在学习"+book);
}
}