构造一个学生类。学生有名字,出生年份和毕业时间。学生可以计算毕业年龄,说话。
public class Student { // Student 类
String name;
int birthYear;
static int graduationYear = 2022;
Student(String name){
this.name = name;
}
int getGraAge(){
return graduationYear-birthYear;
}
String talk(String world){
return world;
}
}
每一部分都代表什么意思?有什么作用呢?
解释如下:
public class Student { // Student 类
// --------------------以下是成员变量,field variable ---------------------
String name;
int birthYear;
static int graduationYear = 2022; //静态变量,所用对象(object)共享的默认值
// --------------------以下是构造函数,constructor--------------------------
Student(String name){ //这里的name是‘形式参数’
this.name = name; // this.name 指向上面的‘成员变量’
}
// 用于初始化变量
// 按住ctrl键,把鼠标放在任意name单词上。可以看见与之相关的name
// IDEA中可以使用右键快速生成构造函数
//---------------------以下是成员方法,field method------------------------
int getGraAge(){
return graduationYear-birthYear;
}
String talk(String world){
return world;
}
}
/**summary:
* 静态static是类(class)具有的属性,
* variable和 method是对象(object)具有的属性
* 比如,this指代的是当前对象(object)。
* static上下文里没有object这个东西,所以static中用不了this关键字
* **/
配合Main函数:
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Mirilla"); // 创建一个学生object,s1
s1.birthYear = 1999;
System.out.println(s1.name+" graduated from college at the age of "+ s1.getGraAge()+".");
Student s2 = new Student("Carrie");// 创建一个学生object,s2
s2.birthYear = 2002;
System.out.println(s2.name+" graduated from college at the age of "+ s2.getGraAge()+" .");
}
}
可以得到如下结果:
Mirilla graduated from college at the age of 23.
Carrie graduated from college at the age of 20 .