关于组合的问题
本帖最后由 ilsoviet1917 于 2022-3-11 08:54 编辑为什么salary打印不出来?
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;
System.out.println(role);
System.out.println(id);
System.out.println(sexual);
}
} 本帖最后由 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);
}
} isdkz 发表于 2022-3-11 08:48
可以打印出来呀,只不过你还没设置初始值而已,所以默认初始值就是 0 了
public void Person(){
job.setSalary(10000);
}
这里不算设置初始值了吗? 本帖最后由 isdkz 于 2022-3-11 09:07 编辑
ilsoviet1917 发表于 2022-3-11 08:56
public void Person(){
job.setSalary(10000);
}
你只是定义了一个方法,你又没有去调用它,构造方法才会自动去调用,
在 Employee 类里面,Employee 才是它的构造方法,
普通的方法你要么在主方法里面去显式调用,要么在构造方法里面显式调用
页:
[1]