定义一个正方形类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的面积并输出
输入格式:
输入在一行中给出边的值。
输出格式:
输出s1对象的边、输出s1对象的面积
输出s2对象的边、s2对象的面积
输入样例:
在这里给出一组输入。例如:
3
-5
输出样例:
在这里给出相应的输出。例如:
this is constructor method
s1:edge=2
s1:area=4
this is constructor method
s2:edge=3
s2:area=9
this is constructor method
s1:edge=2
s1:area=4
this is constructor method
s2:edge=1
s2:area=1
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
import java.util.*;
import java.util.Set;
class square
{
private int edge;
public square()
{
this.edge= 2;
System.out.println("this is constructor method");
}
public int setEdge()
{
Scanner scanner= new Scanner(System.in);
int edge= scanner.nextInt();
scanner.close();
if(edge<=0)
{
this.edge= 1;
}
else
{
this.edge = edge;
}
return this.edge;
}
public int getEdge()
{
//怎样调用方法
return edge;
}
public int getArea()
{
return edge*edge;
}
}
public class Main
{
public static void main(String [] args)
{
square s1= new square();
System.out.println("s1:edge="+s1.getEdge());
System.out.println("s1:area="+s1.getArea());
square s2= new square();
System.out.println("s2:edge="+s2.setEdge());
System.out.println("s2:area="+s2.getArea());
}
}