如何编写一个职员类Employee,要求:具有成员变量姓名name(String)、性别sex(char
年龄age(int);具有成员方法自我介绍String introduction();职员的最小年龄要求为20岁。编写测试类Test3,创建职员类的对象tc,进行introduction方法的调用,显示职员的年龄是否符合要求。
提示:要满足职员的最小年龄要求,可通过对属性的封装来实现。
class Employee {
String name;
char sex;
int age;
Employee(String name, char sex, int age) throws Exception{
this.name =name;
this.sex =sex;
if(age < 20) {
throw new Exception("年龄不符合要求");
}
this.age =age;
}
String introduction(){
return "姓名:" + name + " 性别:" + sex + " 年龄:" + age;
}
}
public class Test3 {
public static void main(String[] args) {
try{
Employee tc = new Employee("张三", 'F', 19);
System.out.println(tc.introduction());
} catch(Exception e) {
e.printStackTrace();
}
}
}
太简单了
public class Employee
{
String name;
char sex;
int age;
public Employee(String name, char sex, int age)
{
this.name = name;
this.sex = sex;
this.age = age;
}
public String introduction(){
if (age >= 20){
return "我叫" + name + ",今年" + age + "岁,性别:" + sex + ", 达到工作年龄。";
}else{
return "我叫" + name + ",今年" + age + "岁,性别:" + sex + ", 未达到工作年龄。";
}
}
public static void main(String[] args)
{
Employee tc = new Employee("小明", '男', 19);
System.out.println(tc.introduction());
}
}
这都是定义,都是安装要求根据语法写的事,只需要在设置年龄的时候加个判断