构造方法的定义:
构造方法也叫构造器或者构造函数
构造方法与类名相同,没有返回值,连void都不能写
构造方法可以重载(重载:方法名称相同,参数列表不同)
如果一个类中没有构造方法,那么编译器会为类加上一个默认的构造方法。
默认构造方法格式如下:
public 类名() {
}
如果手动添加了构造器,那么默认构造器就会消失。
建议代码中将无参构造器写出来。
public class Student {
public String name;
public int age;
public void eat() {
System.out.println("eat....");
}
//构造器
/**
* 名称与类名相同,没有返回值,不能写void
* 构造器可以重载
* 如果类中没有手动添加构造器,编译器会默认再添加一个无参构造器
* 如果手动添加了构造器(无论什么形式),默认构造器就会消失
*/
public Student() {
System.out.println("无参构造器");
}
public Student(int a) {
System.out.println("一个参数的构造器");
age = 15;
}
public Student(int a, String s) {
System.out.println("两个参数的构造器");
age = a;
name = s;
}
构造方法的作用:
构造方法在创建对象时调用,具体调用哪一个由参数决定。
构造方法的作用是为正在创建的对象的成员变量赋初值。
public class Test {
public static void main(String[] args) {
//调用无参构造器
Student s1 = new Student();
//调用有参构造器
Student s2 = new Student(15);
System.out.println(s2.age);
Student s3 = new Student(34, "小明");
System.out.println(s3.name + ":" + s3.age);
}
构造方法种this的使用:
构造方法种可以使用this,表示刚刚创建的对象
构造方法种this可用于
this访问对象属性
this访问实例方法
this在构造方法中调用重载的其他构造方法(要避免陷入死循环)
只能位于第一行
不会触发新对象的创建
public class Student {
public String name;
public int age;
public void eat() {
System.out.println("eat....");
}
//构造器
//使用this()调用重载构造器不能同时相互调用,避免陷入死循环
public Student() {
//this()必须出现在构造器的第一行,不会创建新的对象
this(15);//调用了具有int类型参数的构造器
System.out.println("默认构造器");
}
public Student(int a) {
this.eat();
eat();//this.可以省略
}
//this在构造器中表示刚刚创建的对象
public Student(int a, String s) {
System.out.println("两个参数的构造器");
this.age = a;
this.name = s;
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(15, "小明");
System.out.println(s1.name + ":" + s1.age);
Student s2 = new Student(12, "小红");
System.out.println(s2.name + ":" + s2.age);
Student s3 = new Student();
}
归纳this在实例方法和构造方法种的作用
this是java多态的体现之一
this只可以在构造方法和实例方法种存在,不能出现在static修饰的方法或代码块中
this在构造方法中表示刚刚创建的对象
this在实例方法种表示调用改方法的对象
this可以在实例方法和构造方法中访问对象属性和实例方法
this有时可以省略
this可以在实例方法中作为返回值
this可以当作实参
this可调用重载的构造方法