在创建对象的时候自动调用的方法
语法:
public 类名(传参){
}
注意:
1.没有返回值这一项,也就是void
2.在我们执行new的时候,自动调用构造方法
3.每一个类都会存在一个默认的构造方法,当你设置了自己的构造方法,那这个默认的无参构造方法就会自动消失。
注意:必须在构造方法写this,color……否则
//这是没在构造方法里写this的
package com.huyuhao.twoDay;
public class Car {
String color;
int speed;
int seat =5 ;
//每一个类都会自动生成默认构造方法
//在创建对象的时候自动调用
public Car(String color, int speed){
}
public void run(){
System.out.println(this.color+"颜色的车在跑");
}
public static void main(String[] args) {
Car c1 = new Car("红色",120); //调用默认的构造方法
// c1.color = "红色";
// c1.speed = 120;
Car c2 = new Car("绿色",180);
// c2.color = "绿色";
// c2.speed = 180;
c1.run();
c2.run();
}
}
下面是效果图