Reputation: 125
I'm just going through inner classes but I'm getting the wrong output.
I'm basically trying to create a student object with two different addresses using an address class but I'm getting some ridiculous output. I'm clearly doing something completely wrong so if anyone could help that would be brilliant.
Student class:
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet, int uniNumber, String uniStreet) {
this.name = name;
homeAddress = new Address(houseNumber, homeStreet);
uniAddress = new Address(uniNumber, uniStreet);
}
public void setUniAddress (Address uniAddress){
this.uniAddress = uniAddress;
}
public class Address {
public int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
}
public String toString() {
String a = name + "\n" + homeAddress + " " + uniAddress;
return a;
}
}
and my test student class to create the object and to run the toString:
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("Cathy", 21, "Smithfield Drive", 72, "Nottingham Drive");
Student.Address anotherAddress
= s1.new Address(8, "Deerfield Way");
System.out.println(s1.toString());
}
the output i'm getting is: Cathy
student.Student$Address@2760e8a2
student.Student$Address@4b48f7e0
Thanks
Upvotes: 1
Views: 105
Reputation: 3016
You need to implement the toString()-Method of Adress as well.
public class Address {
public int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
public String toString() {
return street + Integer.valueOf(number);
}
Upvotes: 2
Reputation: 206836
If you want nice output instead of something like Cathy student.Student$Address@2760e8a2
, then you need to override the toString()
method in your class Address
.
Currently, the toString()
method that you have is in class Student
, not in class Address
- carefully check the {
and }
.
Upvotes: 2