构造方法

构造方法

构造方法是专门用来创建对象的方法,当我们通过关键字new来创建对象时,其实就是在调用构造方法.

构造方法的定义格式:

   public 类名称( [参数类型 参数名称 , ........] ){
     方法体
   }

注意事项:

  1. 构造方法的名称必须和所在的类名称完全一样,就连大小写也要一样

  2. 构造方法不要写返回值类型,连void都不用写

  3. 构造方法不能return一个具体的返回值

  4. 如果没有编写如何构造方法,那么编译器将会默认定义一个空构造方法:

      public 类名 (){};

  5. 一旦编写了至少一个构造方法,那么编译器将不再提供默认的构造方法.

  6. 构造方法也是可以重载的.

    重载:方法名相同,参数列表不同;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

public class Main02{
public static void main(String[] args) {
//默认构造函数
Student student1 = new Student();
//全参构造函数
Student student2 = new Student("赵敏",20);

System.out.println("姓名: " + student2.getName() + "年龄: " + student2.getAge());
//修改年龄
student2.setAge(21);

System.out.println("姓名: " + student2.getName() + "年龄: " + student2.getAge());

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

public class Student{

//私有成员变量
private String name;
private int age;
//无参构造方法
Student(){
System.out.println("无参构造方法被调用");
};
//全参构造方法
Student(String name,int age){
this.name = name;
this.age = age;
}
//设置name
public void setName(String name){
this.name = name;
}
//获取name
public String getName(){
return this.name;
}
//设置age
public void setAge(int age)
{
this.age = age;
}
//获取age
public int getAge(){
return this.age;
}

}