day06-面向对象-封装的优化_this的使用

This commit is contained in:
2026-01-19 11:25:48 +08:00
parent f1c23824f8
commit a1960a6a27
2 changed files with 23 additions and 10 deletions

View File

@@ -10,6 +10,7 @@ public class Demo04 {
public static void main(String[] args) { public static void main(String[] args) {
//创建一个学生,并给学生设置属性值,展示该学生 //创建一个学生,并给学生设置属性值,展示该学生
Student s = new Student(); Student s = new Student();
System.out.println("s的地址"+s);//s中保存的是地址
//设置属性 //设置属性
//s.name = "张三"; //s.name = "张三";
s.setName("张三"); s.setName("张三");

View File

@@ -26,21 +26,33 @@ public class Student {
return name; return name;
} }
public void setName(String s){
name = s;//对属性进行赋值
}
//定义变量,要见其名,知其意
public void setName(String name){
/*
当前代码想要的效果:成员变量 = 局部变量
但当前的效果:局部变量 = 局部变量
如何解决当前重名的问题???
使用thisthis.成员变量名,一定表示当前对象的成员变量
this:表示一个对象哪个对象调用了当前的方法那么这个this就表示该对象
*/
//name = name;局部变量name赋值给了局部变量name就近原则
System.out.println("this的内容"+this);
//注意类中的所有的成员前面都应该加上this.,如果没加,编译器会帮我们自动加上
this.name = name;//name属性 = name局部变量
}
public int getAge(){ public int getAge(){
return age; return age;
} }
public void setAge(int age){
public void setAge(int a){ if (age < 0||age >100) {
if (a < 0||a >100) {
System.out.println("您传递的年龄有误只能是0~100的值"); System.out.println("您传递的年龄有误只能是0~100的值");
//不对当前的属性进行赋值(让方法提前结束) //不对当前的属性进行赋值(让方法提前结束)
return;//结束方法,如果有返回值,就会把值返回 return;//结束方法,如果有返回值,就会把值返回
} }
age = a;//对属性进行赋值 this.age = age;//对属性进行赋值
} }
@@ -48,17 +60,17 @@ public class Student {
//吃饭 //吃饭
public void eat(String food) { public void eat(String food) {
System.out.println(name+"学生在吃饭,吃"+food); System.out.println(this.name+"学生在吃饭,吃"+food);
} }
//睡觉 //睡觉
public void sleep() { public void sleep() {
System.out.println(name+"学生在睡觉"); System.out.println(this.name+"学生在睡觉");
} }
//学习 //学习
public void study(String book) { public void study(String book) {
System.out.println(name+"学生在学习,学"+book); System.out.println(this.name+"学生在学习,学"+book);
} }
public void show() { public void show() {