I have an array with objects inside. How would I use methods on the array element?
My array is of type Object. I tried array[i].getSalary() but this doesn’t work.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First of all, you should almost never use an array of
Object. The reason is that you lose all type information that :Instead of an array of
Object, use an array of the type corresponding to the types of the object that will be put inside it (or a common base class). Assuming that your class is calledEmployee, you should declare your array this way:(
employeeArrayis a better name thanarraybecause it tells what kind of objects it contains, again for readability. In general, prefer explicit names for variables.)With that solution it is easy to use
employeeArray[i].getSalary(), if the classEmployeecontains such method. The intention of this code is also obvious when you read it.Other possibilities are generic collections like
List<Employee>orSet<Employee>, depending on your needs.If you really have to use an array of Object, and call a
getSalary()method, you will have to cast the array elements to the class or interface to which the methodgetSalary()belongs.For example and again, if this class is called
Employee:What casting does is obtaining a reference of type Employee of your object. The object is still the same but now you can call methods of
Employeeon this object.But this solution have a number of caveats. First, it is more verbose and it takes two lines to make what could have taken just one. Second, and more importantly, since you have an array of
Object, you can not be certain that you really have an object of typeEmployee, and if it is not the case, the operation will throw aClassCastException. A solution to this is to first check that the object is really of the desired type:But you see that it becomes much more verbose and if you multiply this by the number of times you will have to call a method of these objects, then the code becomes unmanageable.