一.构造方法:
在创建对象时,自动调用的方法:
语法:
public 类名(传参){
}
注意:
1.没有返回值这一项
2.在我们new的时候,自动调用构造方法
作用:在创建对象的时候,给对象设置属性信息。
Java会默认自动地赠送给每一个类一个无参数的构造方法,但是,如果写了构造方法,系统就不再赠送。
public class car {
//成员变量
String color;
int speed;
int seat = 5;
//成员方法
public car(String color,int speed){ //调用有参构造
this.color = color;
this.speed = speed;
}
public void run() {
System.out.println(this.color+"车能跑");
}
public void fly(String color) {
System.out.println(this.color+"的车在"+color+"的云里面跑");//this代指对象的
}
public static void main(String[] ages) {
car Ferrari = new car("绿色",200); //初始化
Ferrari.run();
car Benz = new car("褐色",180);
Benz.run();
}
}
二.构造方法的重载:
构造方法也可以进行重载
作用:可以有更多的方式来创建对象
使用this可以访问其他的构造方法
注意:this()
public class daxia {
String name;
String waihao;
int age;
String bangpai;
//需要两个构造方法
public daxia(String name, int age,String bangpai){
this.name= name;
this.age= age;
this.bangpai= bangpai;
}
public daxia(String name, int age,String bangpai, String waihao){
this(name, age, bangpai); //this还可以调用当前类的其他的构造方法
this.waihao= waihao;
}
public static void main(String[] args){
daxia a = new daxia("岳不群",18,"华山派");
daxia b = new daxia("武松",18,"梁山","行者");
}
}