-4

Im unable to get the mark attribute of Student and dont understand why.

public class StudentTest
{
    public static int numberPassed(List students)
    {
        int count =0;
        for( int i = 0; i < students.size();i++  )
        {
        System.out.println(students.get(i).mark);
        }
        return count;
}
eire
  • 21
  • 6

1 Answers1

0

In Java, every List holds objects, so operation list.get(i) will return an Object. If you want to do some action on Student class instance, you need to check if this object is a Student class instance., then cast it to Student class.

If your lists holds only students, you can add a generic type to it like so: List<Student> stidents. Then operation list.get(i) will return a Student instance. But this goes both ways, you can only add Student objects to this list.

In short, you have two choices:

Use generic list type:

public static int numberPassed(List<Student> students){
      ...
}

or cast:

Student student = (Student)students.get(i);
System.out.println(student.mark);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Beri
  • 11,470
  • 4
  • 35
  • 57