05_10Java笔记
05_10
构造方法:是一种特殊的方法。
主要功能是用来在创建对象时初始化对象,即为对象成员变量赋初始值
构造方法必须与类名相同,在方法名前面不声明方法类型,可以重载多个不同的构造方法
快捷键: alt + shift + s 选择generate constructor using fields
publicclass carcar {
publicstaticvoid main(String[] args) {
// TODOAuto-generated method stub
Car1 c1 = new Car1(20,"红色");
Car1 c2 = new Car1("黑色","保时捷");
//c1.run(c2);
c2.run(c1);
}
}
class Car1{
inthight;
String color,pinp;
public Car1() {}
public Car1(inthight,String color) {
this.hight = hight;
this.color = color;
}
public Car1(String color,String pinp) {
this.color = color;
this.pinp = pinp;
}
publicvoid run(Car1 car) {
System.out.println("一个"+this.color+"高度"+ car.hight+"品牌"+ this.pinp+"的车在开");
}
}
运行结果:一个黑色高度20品牌保时捷的车在开
publicclass Ex_a {
publicstaticvoid main(String[] args) {
// TODOAuto-generated method stub
wide an1 = new wide("兔子","草",5);
wide an2 = new wide();
wide an3 = new wide(an1,an2);
an2.all(an3);
}
}
class wide{
String name;
String eat;
intweight;
public wide() {
this.name = name;
this.eat = "猪蹄";
this.weight = 12;
}
public wide(wide a,wide b) {
this.name = b.name;
this.eat = a.eat;
this.weight = b.weight;
}
public wide(String name,String eat,intweight) {
this.name = name;
this.eat = eat;
this.weight = weight;
}
public wide(String name,intweight) {
this.name = name;
this.weight = weight;
}
publicvoid eat1() {
System.out.println("这个动物喜欢吃" + this.eat);
}
publicvoid run() {
System.out.println("这个动物会跑");
}
publicvoid all(wide an) {
System.out.println("这是一只 " + this.name + ",它喜欢吃 " + an.eat + ",它重 " + an.weight +" 斤");
}
}
运行结果:这是一只 null,它喜欢吃草,它重 12 斤