如何从Java中的其他类访问对象的私有数组?

问题描述 投票:-5回答:1

对象的私有数组private array of objects

因此,以上提到显示了已声明的对象私有数组。在这两个对象数组中,我存储了“客户”和“员工”的一些价值。现在,我想将其存储的值用于另一个类。如果我想按索引访问这些对象数组,将如何处理?

java arrays object private
1个回答
0
投票

您必须为这两个私有数组创建get方法

public Customer[] getCustomers() {
   return customers;
}

public Employee[] getEmployees() {
   return employees;
}

这样,您可以从其他班级访问它们。或者,如果您想从特定索引中获取值。

public Customer getCustomer(int index) {
   return customers[index];
}

public Employee getEmployee(int index) {
   return employees[index];
}

但是在这种情况下,您还必须处理IndexOutOfBoundException情况。为避免此错误,一种方法是检查索引是否小于数组的长度且大于零,否则将返回null值。

public Customer getCustomer(int index) {
  if(index >= 0 && index < customers.lenght) {
     return customers[index];
  }

  return null; 
}

public Employee getEmployee(int index) {
   if(index >= 0 && index < employees.lenght) {
     return employees[index];
   }

   return null;
}
© www.soinside.com 2019 - 2024. All rights reserved.