【构造方法】Java中this的用法和构造方法实例
本人以学生为对象举例说明this在构造方法中的应用,还有对重载的实例练习。
具体实现:
package basic;
/*
* Author:Tang.Mitnck
* Site:FaFu
* Goal:练习this关键字在构造方法中应用并熟悉构造方法
* */
/*
* 设计思想:建立一个student类,并为其添加相应的构造方法,在添加构造方法时我会用到重载*/
class Who{
public static void main(String[] args){
Student a=new Student();
Student b=new Student(9527,"华安");
Student c=new Student(9530,"詹姆斯邦德",30);
a.massage();
b.massage();
c.massage();
}
}
public class Student {
private int id;
private String name;
private int age;
Student(){
}
//用this来区分局部变量和成员变量
Student(int id,String name){
this.id=id;
this.name=name;
}
Student(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
}
public void massage(){
System.out.println("id="+this.id+
"\n"+"name="+this.name+"\n"+"age="+this.age+"\n");
}
}
结果输出: