编程问题为什么会出现两个null
package company; import staff.CompanyStaff; public class Text { public static void main(String[] args) { CompanyStaff staff = new CompanyStaff("张铭","S001","男",29,"经理","人事部"); String s = staff.infor(); System.out.println(s); } }
package staff; public class CompanyStaff { private String name; private String number; private String sex; private int old; private String department; private String post; public CompanyStaff(){ } public CompanyStaff(String name,String number,String sex,int old,String post,String department){ this.setName(name); this.setOld(old); this.setSex(sex); this.setNumber(number); this.post = post; this.department = department; } Post staffPo = new Post(post); Department staffDep = new Department(department); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getOld() { return old; } public void setOld(int old) { if(old >=18 && old<=65) this.old = old; this.old = 18; } public String infor(){ String str = "姓名:"+this.getName()+"\n工号:"+this.getNumber()+"\n性别:"+this.getSex()+"\n年龄:"+this.getOld()+"\n职务:"+staffDep.getDepartment()+staffPo.getPostName(); return str; } }
package staff; public class Department { private String department; public Department(){ } public Department(String department){ this.setDepartment(department); } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } }
package staff; public class Post { private String postName; public Post(){ } public Post(String postName){ this.setPostName(postName); } public String getPostName() { return postName; } public void setPostName(String postName) { this.postName = postName; } }
为什么打印出来的职务是两个null,我想出了一个方法可以打出正确结果,但是这里想不通,我就直接提交了这个,结果才知道只有两次提交机会,而且也没有办法告诉老师我想问这个问题,又浪费了一次机会,还会让老师以为我不做完就交,这么垃圾呀,想想就好气哟,有没有人帮我看看问题出在哪里了,谢谢了
34
收起
正在回答
3回答
按照代码的执行顺序,方法外的代码会优先执行,然后会执行构造方法里的代码。因此下面两行代码在执行的时候post和department还没有赋值,因此都为null:
Post staffPo = new Post(post);
Department staffDep = new Department(department);
jiangkerLove
2017-02-16 22:36:26
Post staffPo = new Post(post); Department staffDep = new Department(department);
老师,是不是在CompanyStaff被调用的时候这两句是不会允许的哟,才导致了结果出现了两个null?
Android零基础入门2018版
- 参与学习 人
- 提交作业 5461 份
- 解答问题 7238 个
此次推出的专题为Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始学习Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星