day06-面向对象--封装-this关键字使用

This commit is contained in:
2025-12-26 15:49:23 +08:00
parent 6a790d9ab5
commit 113268db98
2 changed files with 21 additions and 8 deletions

View File

@@ -4,7 +4,6 @@ public class Student {
private String name;
private int age = 20;
private int id;
//学习
public void study(String book) {
System.out.println("学号:"+id+",姓名:"+name+",年龄为"+age+"岁的学生在学"+book);
@@ -14,30 +13,43 @@ public class Student {
public String getName(){
return name;
}
//在开发中,定义变量尽量增强可读性,见其名知其意
public void setName(String name){
/*
当前代码想要的意思:成员变量 = 局部变量;
当前的意思却是:局部变量 = 局部变量;
注意:当成员变量与局部变量重名时!!!就近原则
public void setName(String n){
name = n;
如何解决当前的重名问题??
使用thisthis.成员变量名,这样就表示的是当前对象的成员变量
this:方法中的对象指的是哪个对象调用该方法那么这个this就表示该对象
this的作用区分成员变量与局部变量
*/
System.out.println(this);
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int a){
public void setAge(int age){
//增加数据的安全性的判断功能
if (a < 1||a>120) {
if (age < 1||age>120) {
System.out.println("您输入的年龄非法的");
return;
}
age = a;
this.age = age;
}
public int getId(){
return id;
}
public void setId(int i){
id = i;
//shift+f6:修改名称
public void setId(int id){
this.id = id;
}
}

View File

@@ -15,6 +15,7 @@ public class StudentTest {
public static void main(String[] args) {
//创建一个学生对象
Student s = new Student();
System.out.println(s);
s.study("java");
//s.属性 = 值
//对象的属性的设置值