构造方法是在实例化对象时调用的。而且实例化时转达的参数必须有构造方法的参数同等。
例如:
class Student { String name; int score; String no; Student(String name1,int score1){ name= name1; score= score1; }}public class StudentTest { public static void main(String[] args) { Student s1 =new Student("haha",76);//调用student类的构造方法,为name和score属性初始化,no为默认值null }}留意:构造方法不答应通过对象名调用。
6.5 构造方法的重载
class Student{ String name; int score; String no; //第1种构造方法的重载 Student(String name1, int score1){ name = name1; score = score1; } //第2种构造方法的重载 Student(String name1, int score1, String no1){ name = name1; score = score1; no = no1; } public void play(){ System.out.printf("我的名字是%s,我的结果是%d,我的学号是%s",name ,score ,no); System.out.println(); }}public class StudentTest { public static void main(String[] args) { Student s1 = new Student("yaya",78);//调用第1种构造方法的重载 s1.play(); Student s2 = new Student("haha", 98,"111");//调用第2种构造方法的重载 s2.play(); }}7 this关键字
7.1 this关键字的使用
在类中,如果类的属性名和方法内部的局部变量同名时,那么在方法内部使用的是局部变量,也就是变量使用依照就近原则,例如:
Student(String name,int score){ name = name; score = score;此时,就无法判断name的指代了,云云看来类的属性名和构造方法的参数名称不能类似。
但使用this关键字就能使类的属性名和构造方法的参数名称类似。使用示例如下:
class Student{ String name; int score; String no; Student(String name,int score){ //this代表正在运行的对象,当实行第16行代码时,调用了构造函数,此时this代表第16行的s1 this.name = name; //this.name指的是对象的属性,name是指方法的参数 this.score = score; //this.score指的是对象的属性,score是指方法的参数 } public void play(){ System.out.printf("我的名字是%s,我的结果是%d,我的学号是%s",name ,score ,no); }}public class StudentTest { public static void main(String[] args) { Student s1 = new Student("yaya", 78); s1.play(); }}运行效果:
7.2 this关键字的省略
在非static方法内部使用属性,可以省略,例如:
public void sayHello(){ System.out.printf("我是%s,我的结果是%d,我的学号是%s",this.name,this.score,this.no);}可以写成
public void sayHello(){ System.out.printf("我是%s,我的结果是%d,我的学号是%s",name,score,no);}7.3 this调用重载方法