java构造函数实现代码示例

java构造函数实现代码示例

复制代码 代码如下:

public class TestCar {

public static void main(String[] args) {

Car c1 = new Car();

r = "red";

d = "xxx";//如果这辆汽车有很多属性,这样一一赋值不是很麻烦?有没有办法一生产出来就设定它的属性(初始化)吗?有~~~看下面

}

}

class Car {

String color;

String brand;

void run() {

tf("I am ing~~~~n");

}

void showMessage() {

tf("汽车颜色:%s, 汽车品牌:%sn", color, brand);

}

}

改进后的Car_

复制代码 代码如下:

/*什么是构造方法*/

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) {

r = color; //这里的this是这个对象的意思.第一个color是这个对象的color属性,第二个是局部变量color

d = brand; //同上

}

void run() {

tf("I am ing~~~~n");

}

void showMessage() {

tf("汽车颜色:%s, 汽车品牌:%sn", color, brand);

}

}