this指针
接着你写的 Student 类,今天把 this、`private`、`static` 的区别弄清楚。先不加新功能,用你已经写过的代码理解它们。
this表示当前正在操作的对象。
如果参数换个名字,可以不写 this:
Student(String studentName, int studentScore) {
name = studentName;
score = studentScore;
}
private 限制外部直接访问成员。
static 表示成员属于类,由所有对象共享。
静态方法不能访问普通成员变量,因为没有办法指定读取某个对象的数据。要这么读的话应该变成实例方法,通过对象调用才能读谁的。
小练习,这个输出多少?
java
public class Main {
public static void main(String[] args) {
Student a=new Student(90);
Student b=new Student(80);
a.showInfo();
b.showInfo();
}
}
class Student{
private static int score;
Student(int score){
Student.score=score;
}
void showInfo(){
System.out.println("score:"+score);
}
}
显然都是80。
不过我在此有了个疑问,Student这个构造函数,不能写this.score=score了吗?
可以这样写,能编译,但当 score 是静态字段时,不推荐。因为private static int score表示score属于类,即使通过this.score访问修改的仍然是共享的那一份。
所以这两种写法在这里修改的是同一个字段:
java
this.score = score; // 能用,但容易让人误以为是对象独有的字段
Student.score = score; // 推荐,明确表示这是静态字段
构造方法重载
它能解决你之前遇到的"有时传两个参数,有时传三个参数"的问题。
同一个类可以有多个构造方法,只要参数列表不同。
这叫 重载(overload) ,C++ 中也有这个概念。参数的数量、类型或类型顺序不同,可以形成重载;仅改参数名不算。
java
Student(String name, int score) {
this(name, 20, score);
}
Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
问:this可以通过括号构造参数吗?然后怎么对应到这个20就是age的?
Java 找到参数类型依次为 String、int、int 的构造方法,然后按位置传递。
问:所以这个是严格按照位置定义的吗?如果是int string int,传入这个就会报错?
对,参数严格按位置匹配,而且每个位置的类型必须兼容。
假如你写反了:
this(name, score, 20);
仍然能编译,因为后两个参数都是 int,但会得到:
年龄:90
成绩:20