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
a
tob
, but copying the reference toa
tob
(the memory address). So botha
andb
are references to the object created bynew
.Let's follow your code so you see what's happening:
Here you modified
course
object.matematik
now is also the same ascourse
because it points to same object.Here you modify
course
again. Nowcourse
,turkce
andmatematik
are 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
You need to create a new
Course
object for each course, youraddNewCourse
method only mutates the currentCourse
object. ModifyCourse
like so:And then use the following: