1.变量什么时候定义为成员变量
如果这个变量是用来描述这个类的信息的,那么,该变量就应该定义为成员变量
2.变量的范围越小越好,因为能及时的被回收
3.定义一个长方形类,求周长和面积
然后定义一个Test进行测试
长方形的类
成员变量:长,宽
成员方法:周长,面积
import java.util.Scanner;
class Oblong{
private int length;
private int width;
public Oblong(){
}
public void setLength(int length) {
this.length=length;
}
public void setWidth(int width) {
this.width=width;
}
public int getZhouchang() {
return (length+width)*2;
}
public int getArea() {
return (length*width);
}
}
public class Test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入长的值");
int a=sc.nextInt();
System.out.println("请输入宽的值");
int b=sc.nextInt();
Oblong cfx=new Oblong();
cfx.setWidth(b);
cfx.setLength(a);
System.out.println("周长是"+cfx.getZhouchang());
System.out.println("面积是"+cfx.getArea());
}
}