I have 3 classes: Course, CourseEntry and Transcript. In transcript, I have a function to add courses, like that:
public class Transcript {
CourseEntry coursestaken[] = new CourseEntry[6];
public void addCourse(Course course)
{
coursestaken[lastIndexOf(getCoursestaken())] = new CourseEntry(course);
}
(lastIndexOf gives me the empty array index - it's working on)
And in my CourseEntry:
public class CourseEntry {
Course course;
char grade = 'I';
public CourseEntry(Course course)
{
this.course = course;
}
And in my Course:
public class Course {
int courseNumber,credits;
String courseName;
public Course addNewCourse(int courseNumber, int credits, String courseName)
{
this.courseNumber = courseNumber;
this.credits = credits;
this.courseName = courseName;
return this;
}
In my main:
Transcript t = new Transcript();
Course course = new Course();
Course matematik = course.addNewCourse(1, 2, "Matematik");
t.addCourse(matematik);
Course turkce = course.addNewCourse(1, 4, "Türkçe");
t.addCourse(turkce);
But if I loop coursestaken array, it prints the last inserted index for all.
How can I solve that?
Thanks
Objects are references in Java, that is, pointers to the objects. So when you do:
You’re NOT copying the whole object
atob, but copying the reference toatob(the memory address). So bothaandbare references to the object created bynew.Let’s follow your code so you see what’s happening:
Here you modified
courseobject.matematiknow is also the same ascoursebecause it points to same object.Here you modify
courseagain. Nowcourse,turkceandmatematikare all referencing the same object, which you created first withCourse course = new Course();.I think most easy way to fix this is that you create a constructor with parameters:
and then