数组与其他类 - 对象 - Java [英] Array withother classes - object - Java
问题描述
我有3个课程:课程
, CourseEntry
和 Transcript
。在成绩单中,我有一个功能添加课程,如:
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)
在 CourseEntry
:
public class CourseEntry {
Course course;
char grade = 'I';
public CourseEntry(Course course)
{
this.course = 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;
}
在我的主页:
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);
但如果我循环coursestaken数组,它打印所有的最后插入的索引。
But if I loop coursestaken array, it prints the last inserted index for all.
我如何解决这个问题?
How can I solve that?
感谢
推荐答案
>在Java中,即指向对象的指针。所以当你这样做:
Objects are references in Java, that is, pointers to the objects. So when you do:
Object a = new Object();
Object b = a;
您不是复制整个对象 a
到 b
,但将 a
的引用复制到 b
(内存地址)。因此 a
和 b
是对由 new $ c $
You're NOT copying the whole object a
to b
, but copying the reference to a
to b
(the memory address). So both a
and b
are references to the object created by new
.
让我们按照您的代码,看看发生了什么:
Let's follow your code so you see what's happening:
Course course = new Course();
Course matematik = course.addNewCourse(1, 2, "Matematik");
this.courseNumber = courseNumber;
this.credits = credits;
this.courseName = courseName;
return this;
在此处修改 course
对象。 现在也与
课程
相同,因为它指向同一个对象。
Here you modified course
object. matematik
now is also the same as course
because it points to same object.
Course turkce = course.addNewCourse(1, 4, "Türkçe");
这里可以再次修改 course
现在课程
, turkce
和 matematik
都引用相同对象,您首先创建课程course =新课程();
。
Here you modify course
again. Now course
, turkce
and matematik
are all referencing the same object, which you created first with Course course = new Course();
.
我认为最简单的方法修复这是你创建一个参数的构造函数:
I think most easy way to fix this is that you create a constructor with parameters:
public class Course {
...
public Course(int courseNumber,int credits,String courseName) {
this.courseNumber = courseNumber;
this.credits = credits;
this.courseName = courseName;
}
}
,然后
Course matematik = new Course(1, 2, "Matematik");
t.addCourse(matematik);
Course turkce = new Course(1, 4, "Türkçe");
t.addCourse(turkce);
这篇关于数组与其他类 - 对象 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!