全國(guó)咨詢(xún)/投訴熱線:400-618-4000

首頁(yè)技術(shù)文章正文

使用構(gòu)造方法有哪些注意事項(xiàng)?

更新時(shí)間:2021-09-01 來(lái)源:黑馬程序員 瀏覽量:

IT培訓(xùn)班


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

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

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

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

推薦的使用方式

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

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

重要功能 :

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

示例代碼

/*
學(xué)生類(lèi)
*/
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è)試類(lèi)
*/
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();
}
}







猜你喜歡:

File類(lèi)中常用的構(gòu)造方法【黑馬程序員】

Java 基礎(chǔ)——構(gòu)造器和方法的區(qū)別

Nginx break指令怎么用?

黑馬程序員Java高級(jí)軟件工程師培訓(xùn)

分享到:
在線咨詢(xún) 我要報(bào)名
和我們?cè)诰€交談!