赞
踩
题目描述:
代码:
- class Employee{
- private long number; //员工号
- private String name; //姓名
- private double salary; //薪水
- private String depart; //部门
- //利用getter和setter
- public void setNumber(long number) {
- this.number=number;
- }
- public long getNumber() {
- return number;
- }
- public void setName(String name) {
- this.name=name;
- }
- public String getName() {
- return name;
- }
- public void setSalary(double salary) {
- this.salary=salary;
- }
- public double getSalary() {
- return salary;
- }
- public void setDepart(String depart) {
- this.depart=depart;
- }
- public String getDepart() {
- return depart;
- }
- //构造方法(使用this调用构造方法,极大地简化了代码)
- public Employee() {} //无参
- public Employee(long number) { //单参,只传递员工号
- this(number,"无名氏",0.0,"未定");
- }
- public Employee(long number,String name) { //双参,传递员工号和姓名
- this(number,name,1000.0,"后勤");
- }
- public Employee(long number,String name,double salary,String depart) {
- this.setNumber(number);
- this.setName(name);
- this.setSalary(salary);
- this.setDepart(depart);
- }
- //输出信息
- public void print() {
- System.out.println("公司员工--》 员工号:"+getNumber()+", 员工姓名:"+getName()+", 薪水:"+getSalary()+", 部门:"+getDepart());
- }
- }
- public class Prectice{
- public static void main(String args[]){
- Employee e=new Employee(); //无参
- Employee e1=new Employee(2021070901); //单参,只传递员工号
- Employee e2=new Employee(2021070902,"李华"); //双参,传递员工号和姓名
- Employee e4=new Employee(2021070904,"张三",4000.0,"财务"); //4参,传递员工号、姓名、薪水、部门
- e.print();
- e1.print();
- e2.print();
- e4.print();
- }
- }
结果:(eclipse)
在此代码中,我利用了this关键字来调用构造方法,简化了代码。当然,大家可以直接用此代码中有四个参数的构造方法那样写。
希望对大家有帮助,如果有错误,大家多多指正!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。