我很困惑如何從新的對象實例獲取參數也流入超類來更新超級類中的私有字段。如何將子類參數傳遞給超類私有變量?
所以我在一個高級的Java類,我有家庭作業,需要一個「人」超級類和擴展人的「學生」子類。
Person類存儲學生名稱,但它是接受Person名稱的Student類構造函數。
假設沒有方法在Person中進行變量方法更新... like subClassVar = setSuperClassVar();
EX:
public class Person
{
private String name; //holds the name of the person
private boolean mood; //holds the mood happy or sad for the person
private int dollars; //holds their bank account balance
}
class Student extends Person //I also have a tutor class that will extend Person as well
{
private String degreeMajor //holds the var for the student's major they have for their degree
Public Student(String startName, int startDollars, boolean startMood, String major)
{
degreeMajor = major; // easily passed to the Student class
name = startName; //can't pass cause private in super class?
mood = startMood; //can't pass cause private in super class?
dollars = startDollars; // see above comments
// or I can try to pass vars as below as alternate solution...
setName() = startName; // setName() would be a setter method in the superclass to...
// ...update the name var in the Person Superclass. Possible?
setMood() = startMood; // as above
// These methods do not yet exist and I am only semi confident on their "exact"...
// ...coding to make them work but I think I could manage.
}
}
的作業中的說明,我多少改變,以人的超允許做,所以如果你都相信了良好穩固的行業接受的解決方案涉及的方面是有點模糊改變超類我會做到這一點。
我看到的一些可能的例子是使Person類中的私人變量「protected」,或者在person類中添加setMethods(),然後在子類中調用它們。
我也接受一般概念教育,關於如何將子類contstructor參數傳遞給超類......並且如果可能的話,請在代碼的構造函數部分執行該操作。
最後,我做了四處搜尋,但大部分類似的問題都是非常具體和複雜的代碼....我無法像上面的示例那樣找到任何簡單的東西......也因爲某些原因,論壇帖子沒有聚集所有我的代碼在一起,所以很抱歉上面的混淆閱讀。
謝謝大家。
什麼是超類('Person')構造函數的外觀? 'Person'是否有設置這些'private'字段的方法? – pb2q