java构造函数示例(构造方法)
TestCar.java
public class TestCar {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "red";
c1.brand = "xxx";//如果这辆汽车有很多属性,这样一一赋值不是很麻烦?有没有办法一生产出来就设定它的属性(初始化)吗?有~~~看下面
}
}
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);
}
}
改进后的TestCar_EX.java
/*什么是构造方法*/
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是这个对象的意思.第一个color是这个对象的color属性,第二个是局部变量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);
}
}
相关文章
ElasticSearch学习之ES Mapping实战示例
这篇文章主要为大家介绍了ElasticSearch学习之ES Mapping实战示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-01-01
Spring Native实现0.059s启动一个SpringBoot项目
Spring Native是Spring框架的一个子项目,旨在提供一种将Spring应用程序编译为本地可执行文件的方法,从而提高启动时间和资源效率,本文主要介绍了Spring Native实现0.059s启动一个SpringBoot项目,感兴趣的可以了解一下2024-02-02
SpringCloud开启session共享并存储到Redis的实现
这篇文章主要介绍了SpringCloud开启session共享并存储到Redis的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-02-02


最新评论