老师帮我检查一下。
来源:2-4 编程练习
宝慕林4199460
2022-11-15 22:54:51
public class Employee{ //根据需求完成Employee类的定义 private int id; private String name; private double salary; public Employee(){ } public Employee(int id,String name,double salary){ this.setId(id); this.setName(name); this.setSalary(salary); } public int getId(){ return this.id; } public void setId(int id){ this.id=id; } public String getName(){ return this.name; } public void setName(String name){ this.name=name; } public double getSalary(){ return this.salary; } public void setSalary(double salary){ this.salary=salary; } } import java.util.List; import java.util.ArrayList; public class EmployeeTest { public static void main(String[] args) { //定义ArrayList对象 ArrayList<Employee> empList=new ArrayList<Employee>(); //创建三个Employee类的对象 Employee one=new Employee(1,"张三",5000); Employee two=new Employee(2,"李四",5500d); Employee thr=new Employee(3,"赵六",4000d); //添加员工信息到ArrayList中 empList.add(one); empList.add(two); empList.add(thr); //显示员工的姓名和薪资 System.out.println("员工姓名 员工薪水"); for(int i=0;i<empList.size();i++){ System.out.println(empList.get(i).getName()+" " + empList.get(i).getSalary() ); } } }
问题描述:
为什么不能直接用.name 来获取属性,而是要用getName()
empList.get(i).name
1回答
好帮手慕小小
2022-11-16
同学你好,name属性的访问权限修饰符为private,无法在类外部访问私有的成员,故需使用getName()来获取。同学代码实现符合题目要求,继续加油!
祝学习愉快~
相似问题