引用:https://blog.youkuaiyun.com/zw1996/article/details/52878270
constructor:构造方法
new对象时,都是用构造方法进行实例化的;例如 Animal animal =new Animal();
1\构造方法的方法名必须与类名一样。
2\构造方法没有返回值,不能用void,在方法名前面不能声明方法类型。
3\可以进行重载
单个构造方法
public class Dog {
private String color;
private int height;
public Dog() {
this.color=“red”;
this.height=12;
}
public int getHeight() {
return height;
}
public String getColor() {
return color;
}
}
public class Dog_constructor {
public static void main(String[] args) {
Dog d=new Dog();
System.out.println("狗的颜色:"+d.getColor());
System.out.println("狗的大小:"+d.getHeight());
}
}
上面的代码的包名没复制。
多个构造方法:
public class Dog {
private String color;
private int height;
public Dog() {
this.color="red";
this.height=12;
}
public Dog(String c,int h) {
this.color=c;
this.height=h;
}
public int getHeight() {
return height;
}
public String getColor() {
return color;
}
}
public class Dog_constructor {
public static void main(String[] args) {
Dog d=new Dog();
Dog d1=new Dog();
System.out.println("无参构造方法");
System.out.println("狗的颜色:"+d.getColor());
System.out.println("狗的大小:"+d.getHeight());
System.out.println("有参构造方法");
System.out.println("狗的颜色:"+d1.getColor());
System.out.println("狗的大小:"+d1.getHeight());
}
}