java構(gòu)造函數(shù)示例(構(gòu)造方法)
TestCar.java
public class TestCar {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "red";
c1.brand = "xxx";//如果這輛汽車有很多屬性,這樣一一賦值不是很麻煩?有沒(méi)有辦法一生產(chǎn)出來(lái)就設(shè)定它的屬性(初始化)嗎?有~~~看下面
}
}
class Car {
String color;
String brand;
void run() {
System.out.printf("I am running...running..running~~~~\n");
}
void showMessage() {
System.out.printf("汽車顏色:%s, 汽車品牌:%s\n", color, brand);
}
}
改進(jìn)后的TestCar_EX.java
/*什么是構(gòu)造方法*/
public class TestCar_EX {
public static void main(String[] args) {
Car c1 = new Car("red", "xxx");
}
}
class Car {
String color;
String brand;
public Car(String color, String brand) {
this.color = color; //這里的this是這個(gè)對(duì)象的意思.第一個(gè)color是這個(gè)對(duì)象的color屬性,第二個(gè)是局部變量color
this.brand = brand; //同上
}
void run() {
System.out.printf("I am running...running..running~~~~\n");
}
void showMessage() {
System.out.printf("汽車顏色:%s, 汽車品牌:%s\n", color, brand);
}
}
相關(guān)文章
IDEA報(bào)錯(cuò):Process terminated的問(wèn)題及解決
這篇文章主要介紹了IDEA報(bào)錯(cuò):Process terminated的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11使用IDEA如何打包發(fā)布SpringBoot并部署到云服務(wù)器
這篇文章主要介紹了使用IDEA如何打包發(fā)布SpringBoot并部署到云服務(wù)器問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-1223種設(shè)計(jì)模式(22)java狀態(tài)模式
這篇文章主要為大家詳細(xì)介紹了23種設(shè)計(jì)模式之java狀態(tài)模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01springboot打war包部署到外置tomcat容器的方法
這篇文章主要介紹了springboot]打war包部署到外置tomcat容器,在這需要注意的是在boot-launch.war在tomcat?webapps目錄里面解壓到boot-launch文件夾,感興趣的朋友跟隨小編一起看看吧2022-04-04Netty結(jié)合Protobuf進(jìn)行編解碼的方法
這篇文章主要介紹了Netty結(jié)合Protobuf進(jìn)行編解碼,通過(guò)文檔表述和代碼實(shí)例充分說(shuō)明了如何進(jìn)行使用和操作,需要的朋友可以參考下2021-06-06SpringBoot中的ExpiringMap代碼實(shí)例
這篇文章主要介紹了SpringBoot中的ExpiringMap代碼實(shí)例,ExpiringMap是一個(gè)可以設(shè)置過(guò)期策略、可變條目過(guò)期、延遲條目加載和過(guò)期偵聽器的線程安全存儲(chǔ)容器,需要的朋友可以參考下2023-08-08