JAVA 定义一个正方形类square,在次类中包括写内容: 定义成员变量边长private int edge; 定义方法:包括构造方法,setter getter方法,求面积方法等,要求如下所示: 定义正方形类的构造方法:在构造方法中给edge赋值为2,并添加System.out.println("this is constructor method"); 为成员变量edge设置set方法,用来接收用户给edge的值,如果用户给的值<=0,则设置edge值为1 为成员变量edge设置get方法,用来返回edge的值 完成求面积方法,得到正方形的面积:public int getArea() 定义类Main,并在main方法中, 1.首先创建正方形对象s1,然后通过getEdge()方法输出edge的值,然后调用getArea方法求出s1的面积并输出 2.创建正方形对象s2,并通过键盘输入s2对象的边的值,然后通过getEdge()方法输出edge的值,然后调用getArea方法求出s1的面积并输出
时间: 2023-06-19 15:06:51 浏览: 114
下面是JAVA代码实现:
```
public class Square {
private int edge;
public Square() {
this.edge = 2;
System.out.println("this is constructor method");
}
public void setEdge(int edge) {
if (edge <= 0) {
this.edge = 1;
} else {
this.edge = edge;
}
}
public int getEdge() {
return this.edge;
}
public int getArea() {
return this.edge * this.edge;
}
}
public class Main {
public static void main(String[] args) {
Square s1 = new Square();
System.out.println("s1's edge is " + s1.getEdge());
System.out.println("s1's area is " + s1.getArea());
Scanner scanner = new Scanner(System.in);
Square s2 = new Square();
System.out.print("Please input s2's edge: ");
int edge = scanner.nextInt();
s2.setEdge(edge);
System.out.println("s2's edge is " + s2.getEdge());
System.out.println("s2's area is " + s2.getArea());
}
}
```
阅读全文