public class Rectangle{
public Rectangle() {
//这个就表示无参的构造方法, 在你不写这个构造方法时, 创建对象 时,编译器会编译默认添加无参构造方法
}
public static void main(String[] args) {
Rectangle re =new Rectangle();
}
}
public class Rectangle {
public float length; // 矩形长度
public float width; // 矩形宽度
public Rectangle() {
// 在无参构造方法中给长宽赋值
this.length = 5;
this.width = 10;
}
}
长宽的默认值需要你自己设置 , 我只是举例使用了5 , 10 .
public class Rectangle {
private int length;
private int width;
public Rectangle() {
this.length=10;
this.width=5;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
}
在无参数的默认构造方法中可以初始化一个默认的长和宽,可以根据自己的需求设定
没有参数的构造方法就是无参构造方法,假如你的矩形类叫Rectangle
public class Rectangle {
// 无参构造方法
public Rectangle() {
}
}
默认无参,和自己写的无参是一样的,但是你写了一个非无参数的构造方法,如果需要无参数构造方法,必须自己写
默认的构造方法,就是无参构造方法
public Object(){
}