|
发表于 2022-3-11 08:48:39
|
显示全部楼层
本帖最后由 isdkz 于 2022-3-11 09:00 编辑
可以打印出来呀,只不过你还没设置初始值而已,所以默认初始值就是 0 了
- public class TestComponent {
- public static void main(String[] args){
- Employee e = new Employee("D", 2002, "m");
- System.out.println(e.getSalary());
- System.out.println(e.job.role);
- e.job.setId(513);
- System.out.println(e.job.getId());
- }
- }
- class Job{
- String role;
- long salary;
- int id;
- public String getRole(){
- return role;
- }
- public void setRole(String role){
- this.role = role;
- }
- public long getSalary(){
- return salary;
- }
- public void setSalary(long salary){
- this.salary = salary;
- }
- public int getId(){
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- }
- class Employee{
- Job job = new Job();//组合:一个类用另一个类作为成员
- String sexual;
- public String getSexual(){
- return sexual;
- }
- public void setSexual(String sexual){
- this.sexual = sexual;
- }
- public void setSalary(){job.setSalary(10000);}
- public long getSalary(){
- return job.salary;
- }
- public Employee(String role, int id, String sexual){
- this.job.role = role;
- this.setSalary(); // 注意这里
- System.out.println(role);
- System.out.println(id);
- System.out.println(sexual);
- }
- }
复制代码 |
|