java构造函数示例(构造方法)
程序员文章站
2024-02-27 17:16:03
testcar.java复制代码 代码如下:public class testcar { public static void main...
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);
}
}