day06-面向对象--封装-this关键字使用
This commit is contained in:
@@ -4,7 +4,6 @@ public class Student {
|
|||||||
private String name;
|
private String name;
|
||||||
private int age = 20;
|
private int age = 20;
|
||||||
private int id;
|
private int id;
|
||||||
|
|
||||||
//学习
|
//学习
|
||||||
public void study(String book) {
|
public void study(String book) {
|
||||||
System.out.println("学号:"+id+",姓名:"+name+",年龄为"+age+"岁的学生在学"+book);
|
System.out.println("学号:"+id+",姓名:"+name+",年龄为"+age+"岁的学生在学"+book);
|
||||||
@@ -14,30 +13,43 @@ public class Student {
|
|||||||
public String getName(){
|
public String getName(){
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
//在开发中,定义变量尽量增强可读性,见其名知其意
|
||||||
|
public void setName(String name){
|
||||||
|
/*
|
||||||
|
当前代码想要的意思:成员变量 = 局部变量;
|
||||||
|
当前的意思却是:局部变量 = 局部变量;
|
||||||
|
注意:当成员变量与局部变量重名时!!!就近原则
|
||||||
|
|
||||||
public void setName(String n){
|
如何解决当前的重名问题??
|
||||||
name = n;
|
使用this:this.成员变量名,这样就表示的是当前对象的成员变量
|
||||||
|
this:方法中的对象指的是,哪个对象调用该方法,那么这个this就表示该对象
|
||||||
|
|
||||||
|
this的作用:区分成员变量与局部变量
|
||||||
|
*/
|
||||||
|
System.out.println(this);
|
||||||
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getAge(){
|
public int getAge(){
|
||||||
return age;
|
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("您输入的年龄非法的");
|
System.out.println("您输入的年龄非法的");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
age = a;
|
this.age = age;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getId(){
|
public int getId(){
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(int i){
|
//shift+f6:修改名称
|
||||||
id = i;
|
public void setId(int id){
|
||||||
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ public class StudentTest {
|
|||||||
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.study("java");
|
s.study("java");
|
||||||
//s.属性 = 值
|
//s.属性 = 值
|
||||||
//对象的属性的设置值
|
//对象的属性的设置值
|
||||||
|
|||||||
Reference in New Issue
Block a user