你從來沒有在您的Boy
實例分配給name
任何價值,我已經添加了一些解釋性評論:
// Creates a Person (not a Boy)
Person person = new Person();
// Sets the name on that Person
person.printinfo("WOLFSKIN", "Test Address");
// Creates an *entirely separate object*, an instance of Boy
Boy boy = new Boy();
// Accesses `name`, which has never been set
boy.info();
要在Boy
例如設置name
您Boy
實例,調用printinfo
:
boy.printinfo("WOLFSKIN", "Test Address");
讓我們拋出一些ASCII藝術吧:
Person person = new Person();
給我們:
+-----------+ +-----------------+
| person |---->| Person instance |
+-----------+ +-----------------+
| name: null |
+-----------+ | address: null |
| boy: null | +-----------------+
+-----------+
再經過:
person.printinfo("WOLFSKIN", "Test Address");
我們:
+--------+ +-----------------+ +-----------------+
| person |------>| Person instance | | String instance |
+--------+ +-----------------+ +-----------------+
| name |--->| "WOLFSKIN" |
| address |-+ +-----------------+
+-----------------+ |
+-----------+ | +-----------------+
| boy: null | | | String instance |
+-----------+ | +-----------------+
+->| "Test Address" |
+-----------------+
現在我們做的事:
Boy boy = new Boy();
而得到這樣的:
+--------+ +-----------------+ +-----------------+
| person |------>| Person instance | | String instance |
+--------+ +-----------------+ +-----------------+
| name |--->| "WOLFSKIN" |
| address |-+ +-----------------+
+-----------------+ |
+-----------+ | +-----------------+
| boy |-+ | | String instance |
+-----------+ | | +-----------------+
| +->| "Test Address" |
| +-----------------+
| +-----------------+
+->| Boy instance |
+-----------------+
| name: null |
| address: null |
+-----------------+
注意的是,男孩的實例是由它的超類的字段(Person
,在這種情況下),以及其自己的字段(但它不具有任何)。
由於您從未填寫boy
的name
的值,因此它仍具有默認值null
。
你不明白什麼?您沒有爲該名稱聲明任何值,所以它返回空值是正常的... – realUser404
您沒有爲'boy.name'字段設置任何值,因此它爲空。 「人」和「男孩」實例完全不相關,彼此不瞭解。 –
我從下面的答案(T.J.Crowder)得到它,我假設子類的實例也會繼承超類實例(實例值)。 – WolfSkin