构造方法调用
构造器也叫构造方法(constructor),用于对象的初始化。构造器是一个创建对象时被自动调用的特殊方法,目的是对象的初始化。构造器的名称应与类的名称一致。Java通过new关键字来调用构造器,从而返回该类的实例,是一种特殊的方法。
格式:
[修饰符] 类名(形参列表){
//n条语句
}
要点:
- 通过new关键字调用!!
- 构造器虽然有返回值,但是不能定义返回值类型(返回值的类型肯定是本类),不能在构造器里使用return返回某个值。
- 如果我们没有定义构造器,则编译器会自动定义一个无参的构造函数。如果已定义则编译器不会自动添加!
- 构造器的方法名必须和类名一致!
class Computer {
String brand; //品牌
}
public class SxtStu {
// field
int id;
String sname;
int age;
Computer comp;
void study() {
System.out.println("我正在学习!使用我们的电脑,"+comp.brand);
}
//构造方法
SxtStu() {
}
public static void main(String[] args) {
SxtStu stu1 = new SxtStu();
stu1.sname = "WANG";
Computer comp1 = new Computer();
comp1.brand = "DELL";
stu1.comp = comp1;
stu1.study();
}
}
补充
package TestQuestions;
/**
* @author cc
* @date 2020年3月27日
*
*/
public class FourOne {
private String name;
private int age;
//定义成员方法打印name和age
public void display() {
System.out.println(name + age);
}
//构造方法
public FourOne(String name, int age) {
super();
this.name = name;
this.age = age;
}
public static void main(String[] args) {
FourOne cc = new FourOne("cc", 18);
cc.display();
}
}
构造方法重载
如果方法构造中形参名与属性名相同时,需要使用this关键字区分属性与形参。this.id 表示属性id;id表示形参id
public class User {
int id;
String name;
String pwd;
public User() {
}
public User(int id, String name) {
//super()使用:https://blog.csdn.net/yongbutingxide/article/details/82669054
super();
//方法构造中形参名与属性名相同时,需要使用this关键字区分属性与形参
this.id = id;
this.name = name;
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public static void main(String[] args) {
User u1 = new User();
User u2 = new User(520, "CC");
User u3 = new User(1314, "WANG", "123456");
}
}