内部类,错误的输出

时间:2013-11-07 10:53:35

标签: java inner-classes

我只是在经历内部课程,但是输出错误。

我基本上是尝试使用地址类创建一个具有两个不同地址的学生对象,但是我得到了一些荒谬的输出。我显然做了一些完全错误的事情,所以如果有人能提供帮助那就太棒了。

学生班:

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;
   }
}

和我的test student类创建对象并运行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());
 }

我得到的输出是:凯茜 student.Student$Address@2760e8a2 student.Student$Address@4b48f7e0

由于

2 个答案:

答案 0 :(得分:2)

如果您希望输出效果不是Cathy student.Student$Address@2760e8a2,那么您需要覆盖类toString()中的Address方法。

目前,您拥有的toString()方法位于课程Student,而不是课程Address - 请仔细检查{}

答案 1 :(得分:2)

你需要实现toString() - Adress方法。

 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);
    }