教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

使用構(gòu)造方法有哪些是需要注意的?

更新時(shí)間:2021年09月01日18時(shí)33分 來源:傳智教育 瀏覽次數(shù):

好口碑IT培訓(xùn)

構(gòu)造方法的創(chuàng)建 :

如果沒有定義構(gòu)造方法,系統(tǒng)將給出一個(gè)默認(rèn)的無參數(shù)構(gòu)造方法,如果定義了構(gòu)造方法,系統(tǒng)將不再提供默認(rèn)的構(gòu)造方法。 

構(gòu)造方法的重載 :

如果自定義了帶參構(gòu)造方法,還要使用無參數(shù)構(gòu)造方法,就必須再寫一個(gè)無參數(shù)構(gòu)造方法 :

推薦的使用方式

無論是否使用,都手工書寫無參數(shù)構(gòu)造方法

1630490825058_構(gòu)造方法.jpg

重要功能 :

可以使用帶參構(gòu)造,為成員變量進(jìn)行初始化

示例代碼

/*
學(xué)生類
*/
class Student {
private String name;
private int age;
public Student() {}
public Student(String name) {
this.name = name;
}
public Student(int age) {
this.age = age;
}
public Student(String name,int age) {
this.name = name;
this.age = age;
}
public void show() {
System.out.println(name + "," + age);
}
}
/*
測(cè)試類
*/
public class StudentDemo {
public static void main(String[] args) {
//創(chuàng)建對(duì)象
Student s1 = new Student();
s1.show();
//public Student(String name)
Student s2 = new Student("林青霞");
s2.show();
//public Student(int age)
Student s3 = new Student(30);
s3.show();
//public Student(String name,int age)
Student s4 = new Student("林青霞",30);
s4.show();
}
}



猜你喜歡:

Java中怎樣定義和聲明接口?

Nginx return指令用法介紹【Nginx教程】

搭建社群:確立搭建社群的目的?【新媒體培訓(xùn)】

什么是對(duì)象?JavaSeript對(duì)象詳細(xì)講解

傳智教育Java高級(jí)軟件工程師培訓(xùn)

0 分享到:
和我們?cè)诰€交談!