0

I have a superclass, Student and two subclasses, RStudent and CStudent that inherits from Student. I want to be able to have one ArrayList of both RStudent and CStudent. I tried just using ArrayList<Student> students = new Arraylist<>(); but I can't access any variables that are specific to the subclasses, for example, if I use students.add(newCStudent), when I try use students.get(0).mark (which is a variable only in CStudent) it doesn't work. How can I do this?

0

2 Answers 2

2

You can't have it both ways - if you have a List<Student> to hold both types of Student, you can't access the specific members of RStudent or CStudent without explicitly downcasting. E.g.

// Either check instanceof explicitly, 
// or have some prior knowledge the element is a CStudent:
int mark = ((CStudent) students.get(0)).mark;
Sign up to request clarification or add additional context in comments.

Comments

0
  1. I recommend you declare the reference of generic type, List rather than ArrayList itself e.g. List<Student>.
  2. The superclass, Student is not supposed to know anything about its subclass i.e. in order to access an element of the subclass using the reference of the subclass, you need to tell the compiler that you want to access the element of subclass by using the reference of the superclass and this you do via downcasting i.e. casting the reference of the superclass to the type of the subclass.
  3. It may also be helpful for you to know that you can check the type of object using the operator, instanceof.

e.g.

List<Student> students = new ArrayList<>();

CStudent s1 = new CStudent();
s1.setMark(90);
students.add(s1);

RStudent s2 = new RStudent();
students.add(s2);

//...and so on

for (Student student : students) {
    if (student instanceof CStudent) {// Checking if the instance is of type, CStudent
        CStudent s = (CStudent) student; // downcasting
        System.out.println(s.getMark());// Assuming `CStudent` has `public` getter for mark
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.