1.定义一个长方形类,定义 求周长和面积的方法,然后定义一个测试类进行测试。
分析: 成员变量: 宽width,高high 空参有参构造 成员方法: setXxx和getXxx 求周长:getLength() 求面积:getArea() |
class Test1_Rectangle { //Rectangle矩形
public static void main(String[] args) {
//第一种方式:使用构造方法赋值
Rectangle r = new Rectangle(10,20);
System.out.println(r.getLength()); //周长
System.out.println(r.getArea()); //面积
//第二种方式:使用set方法赋值
Rectangle r2 = new Rectangle();
r2.setWidth(10);
r2.setHigh(20);
System.out.println(r2.getLength()); //周长
System.out.println(r2.getArea()); //面积
}
}
class Rectangle {
private int width; //宽
private int high; //高
public Rectangle(){} //空参构造
public Rectangle(int width,int high) {
this.width = width; //有参构造
this.high = high;
}
public void setWidth(int width) {//设置宽
this.width = width;
}
public int getWidth() { //获取宽
return width;
}
public void setHigh(int high) { //设置高
this.high = high;
}
public int getHigh() { //获取高
return high;
}
public int getLength() { //获取周长
return 2 * (width + high);
}
public int getArea() { //获取面积
return width * high;
}
}
2.定义一个员工类Employee
分析: 成员,然后给出成员变量 |
class Test2_Employee { //employee员工
public static void main(String[] args) {
Employee e = new Employee("张三","9521",20000);
e.work();
}
}
class Employee {
private String name; //姓名
private String id; //工号
private double salary; //工资
public Employee() {} //空参构造
public Employee(String name, String id, double salary) {//有参构造
this.name = name;
this.id = id;
this.salary = salary;
}
public void setName(String name) { //设置姓名
this.name = name;
}
public String getName() { //获取姓名
return name;
}
public void setId(String id) { //设置id
this.id = id;
}
public String getId() { //获取id
return id;
}
public void setSalary(double salary) { //设置工资
this.salary = salary;
}
public double getSalary() { //获取工资
return salary;
}
public void work() {
System.out.println("我的姓名是:" + name + ",我的工号是:" + id + ",我的工资是:" + salary
+ ",我的工作内容是java");
}
}