Jump to content

help with array of objects

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Root23

Root23

    Programmer

  • Members
  • PipPipPipPip
  • 144 posts
I'm having some trouble, and I'm not sure what the problem is. I'm new to Java, but this looks like it should work, yet it doesn't.

I have a superclass called Person that you give a name & birthyear.

Then I have a subclass called Student that uses the Person superclass to give the student a name & birthyear, but also adds a major, student ID, and 'status'. I need 20 students in an array, so I'm having problems there.

The program simply prints out the info in the command prompt.

To start with I construct a person, and print that out. Works fine.
Then I try printing out the students, and it prints out something weird.

Here's the code:

public class test2 {

	public static void main(String[] args) {

	

		Person P = new Person("Perry", 1959);

		System.out.println(P);

		Student[] studentArray = new Student[20];	//	Set up the array

			for (int i=0; i<studentArray.length; i++) {

				studentArray[i] = new Student("name"+i, 1999, "CompSci", 5, 4); 

				System.out.println(studentArray);

			}

	}

}



//SEPARATE CLASSES


class Person {

	private String name;

	private int birthYear;

	public Person(String n, int bYear) {

		name = n;

		birthYear = bYear;

	}

	

	public String toString() {

        return "Person[\nName=" + name + ", \nDOB=" + birthYear + "\n]";

    }

}


class Student extends Person {

	private String major = "";

			int studentID = 0;

			int status = 0;

	

	public Student(String n, int bY, String m, int id, int sta){

		super(n, bY);

		major = m; 

		studentID = id; 

		status = sta;

	}

	

	public String toString() {

		return "Student[" + super.toString() + "\nMajor:" +major + "\nstudentID:" + studentID + "Status:" + status;

	}

}


Like I mentioned above.. the toString for the person prints out fine. However the one for the student just prints out "{LStudent;@187aeca" 20 times.

Could anyone help me out on this, and explain what I'm doing wrong?

Thanks!
Posted Image

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
You print the array
System.out.println(studentArray);
instead of the student inside it:
System.out.println(studentArray[i]);


#3
Root23

Root23

    Programmer

  • Members
  • PipPipPipPip
  • 144 posts
Thanks! That did the trick. I did not even think of that.
+rep
Posted Image