构造方法也有名称,参数,方法体
构造方法与普通方法的区别是:
----构造方法的名称必须与类名相同
----构造方法不能有返回值,也不能返回void
----构造方法必须在创建对象时用new 运算符调用
构造方法定义的基本格式:
[public | protected | private ] ClassName ( [paramList]) {
//方法体
}
public | protected | private 为构造方法的访问修饰符号,用来决定哪些类可以使用构造方法来创建对象,注意,这些访问修饰符与一般方法的用法含义相同。 ClassName 为构造方法的名字,它必须和类名相同,paramList 为参数列表,构造方法可以带有参数。
1.无参数构造方法
无参数构造方法(no-args constructor) 是不带参数的构造方法
public Welcome (){}
像这样就是构造了一个无参的构造方法
使用无参数的构造方法来创建对象,只需在类名后面使用一对括号即可
Welcome calculate = new Welcome(){}
//利用Welcome 类,使用Welcome()构造方法来创建对象,并初始化类的成员变量
构造方法的主要作用是创建对象并初始化类的成员变量。对于成员变量,若在声明时和构造方法的时候没有初始化,那么新创建的对象的成员变量值都被赋值为默认值。对于不同类型的变量的赋值是不一样的:
整型数据 为0 ;浮点型数据的 为0.0 ;字符型数据的默认值为'\u0000' ;布尔类型数据的默认值为 false ,引用类型数据的默认值为 null
2.带参数的构造方法
当然啦,如果你想在创建对象时就给成员变量设置为某个值而不是采用默认值,就可以定义带参数的构造方法
public Welcome (String name ,int age){
System.out.println("the name of the student is " + name );
System.out.println("the age of the student is " + age);
}
既然构造方法已经创建完成,那么如何利用呢?
Welcome student = new Welcome("xiaoming " ,12);
3.默认构造方法
如果在定义类时,没有为类定义任何构造方法,则编译器自动为类添加一个默认的构造方法(default constructor).默认构造方法是无参数的构造方法,方法体为空。
public Welcome(){} //默认构造方法
一旦为类定义了带参数的构造方法,编译器将不会提供默认的构造方法
如果你还使用默认构造方法来创建对象,编译器就会报错
The constructor ******* is undefined
其含义就是没有定义无参数的构造方法,当然啦,如果你想使用默认方法,那么就自己再定义一个啦,也就是默认方法的重载。
4.默认方法的重载
下面定义了三个重载的构造方法
package demo;
public class Welcome{
public static void main(String[] args)
{
Student stu = new Student();
Student stu01 =new Student("mike");
Student stu02 =new Student("mike" ,12);
}
}
class Student{
public Student(){
//无参数的构造方法
System.out.println("This is a no-args constructor");
}
public Student(String name) {
//有一个String 类型的参数
System.out.println("The name of the student is " + name);
}
public Student(String name ,int age) {
System.out.println("The name and age of the student is " + name + ' '+age);
}
}
然后运行结果如下
好啦,构造方法就讲到这里啦!