一、this()语法
this()用在构造方法中,可以通过当前所在的构造方法去调用另一个本类的构造方法。
this(实参);
例如:
public class Demo{
public static void main(String[] agrs){
Student s1 = new Student();
}
}
class Student{
int sno;
String sname;
boolean gender;
public Student(){
this(1,"张三",true);
}
public Student(int sno, String sname, boolean gender){
this.sno = sno;
this.sname = sname;
this.gender = gender;
}
}
- this()只能出现在构造方法第一行。
二、this()语法的作用
- 代码复用。
本文详细解析了Java中this()语法的使用方法及其作用,通过实例展示了如何在一个构造方法中调用同一类的另一个构造方法,实现代码复用。

被折叠的 条评论
为什么被折叠?



