Setter Getter Arrays Java

23,703

You are using Array of Lecture objects and overwriting the same array with two different array references. Hence, it is not working. Use the below code:

    public class Student {
    private Lecture[] lecture;

    public void setStudentLecture(Lecture[] lecture) {
        this.lecture = lecture;
    }

    public Lecture[] getStudentLecture() {
        return lecture;
    }

    public static void main(String[] args) {
        Student student = new Student();
        Lecture[] lectures = new Lecture[3];
        lectures[0] = new Lecture("Physics");
        lectures[1] = new Lecture("Mathematics");
        lectures[2] = new Lecture("Chemistry");

        student.setStudentLecture(lectures);

        Lecture[] lectures1 = student.getStudentLecture();
        for (int i = 0; i <lectures1.length; ++i) {
            System.out.println(lectures1[i].getName());
        }
    }
}

public class Lecture {
    private String name;
    public Lecture(String name) {
        this.name = name;
    }

    public String getName(){
        return name;
    }
}
Share:
23,703
Spongi
Author by

Spongi

Updated on July 18, 2022

Comments

  • Spongi
    Spongi almost 2 years

    Can somebody help me with one little problem. I want to set for example 3 lectures to 1 student, but when i try this i can't set lectures.

    student.setStudentLecture(lecture);
    student.setStudentLecture(lecture1);
    

    public class Student {
        private Lecture[] lecture;
    
        public void setStudentLecture(Lecture[] lecture) {
            this.lecture = lecture;
        }
    
        public Lecture[] getStudentLecture() {
            return lecture;
        }
    }