如何编写一个职员类Employee,要求:具有成员变量姓名name(String)、性别sex(char
年龄age(int);具有成员方法自我介绍String introduction();职员的最小年龄要求为20岁。编写测试类Test3,创建职员类的对象tc,进行introduction方法的调用,显示职员的年龄是否符合要求。
提示:要满足职员的最小年龄要求,可通过对属性的封装来实现。

关于Java封装性的编写设计
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
关注
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(); } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用