构造函数介绍

构造函数

什么是构造方法

构造方法也叫构造函数,或者叫构造器

  1. 构造方法的方法名必须与类名相同
  2. 构造方法没有返回值,也不写void
class Student {
    //构造方法
    Student(){
    }
}

注意:下面这个方法是构造方法吗

class Student {
    void Student(){//普通方法,可有对象调用
    }
    void play(){

    }
}

答:不是

第2行的Student()方法前面添加了void,因此不是构造方法,此时它是一个普通的方法。与play方法一样。可以使用实例化后对象调用Student()方法。

不推荐把普通方法名称定义为与类名相同。

构造方法的作用

类的属性在实例化时被赋予默认值。那么是谁给雷达属性赋的默认值呢???????

class Student {
    String name;
    int score;
    String no;
    
    public static void main(String[] args) {
        Student s1 = new Student();//实例化,此时name,score,no都有默认值了。
    }
}

对象的属性的默认值是由构造方法赋值的。

构造方法的作用:为对象的属性初始化。

默认构造函数

一个类如果没有显示的定义构造函数,那么这个类默认具有无参的构造函数。

默认构造函数为对象的属性赋默认值。

代码示例

class Student {
    String name;
    int score;
    String no;
    public void play(){
        System.out.printf("我的名字是%s,我的成绩是%d,我的学号是%s",this.name,this.score,this.no);
    }
}
public class StudentTest {
    public static void main(String[] args) {
        Student s1 =new Student();
        s1.play();
    }
}

输出结果是:

我的名字是null,我的成绩是0,我的学号是null

为什么输出的是null,0null?

因为本例中没有定义构造函数,系统会自动添加一个默认构造函数,默认构造函数是无参的,会为所有的属性赋默认值,因此name是null,score是0,no是null。

特殊情况:

如果显示的定义了构造函数,那么默认构造函数就消失不存在了。

例如:

class Student {
    String name;
    int score;
    String no;
    //显示定义构造函数,此时默认构造函数就没有了
    Student(){
        
    }
}

构造方法的调用

构造方法是在实例化对象时调用的。并且实例化时传递的参数必须有构造方法的参数一致。

例如

class Student {
    String name;
    int score;
    String no;

    /**
     * 有两个参数的构造方法
     * @param name1
     * @param score1
     */
    Student(String name1,int score1){
        name= name1;
        score= score1;
    }
}
public class StudentTest {
    public static void main(String[] args) {
        Student s1 =new Student("haha",76);//调用student类的构造方法,为name和score属性初始化,no为默认值null
    }
}

构造方法不允许通过对象名调用。例如下面的调用是错误的

 public static void main(String[] args) {
    Student s1 =new Student("haha",76);
    s1.Student("haha",88);//错误的,对象名不允许调用构造函数  
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容