簡體   English   中英

在另一個類的訪問器中調用來自不同類的方法(作業)

[英]Calling a method from a different class within an accessor of another class (homework)

我很難解決這個問題,也很難在網上尋找解決方案。 如何從 CollegeStudent 類中的測試類(測試類不能更改)調用 setYear/setMonth/setDay?

仍然沒有運行測試代碼,因為每當我嘗試運行代碼時都會出現錯誤,因為我需要找到帶有 setYear/setMonth/setDay 的解決方案 :(

如果我對條款有誤,請糾正我

對不起,我的英語不好

MyData 和 CollegeStudent 是我的代碼,而 Test 類來自我的教授,應該用於測試我的代碼

public class Test {

public static void main(String args[]){
    CollegeStudent cs = new CollegeStudent("Cruz","Tom", new MyDate(2014, 6, 1));


    cs.getEnrollmentDate().setYear(2018);
    cs.getEnrollmentDate().setMonth(11);
    cs.getEnrollmentDate().setDay(31);

    cs.getGraduationDate().setYear(2023);
    cs.getGraduationDate().setMonth(3);
    cs.getGraduationDate().setDay(32);
}


public class MyDate{
    private int month, year, day;

    public MyDate(int year, int month, int day){
        this.month = month;
        this.year = year;
        this.day = day;
    }
    public void setYear(int year){
        this.year = year;
    }
    public void setMonth(int month){
        this.month = month;
    }
    public void setDay(int day){
        this.day = day;
    }
}

public class CollegeStudent{
        private String first_name, last_name, enrollment_date, graduation_date;

        public MyDate o;

        public void CollegeStudent(String first_name, String last_name, MyDate mydate){
            this.first_name = first_name;
            this.last_name = last_name;
            o = mydate;
        }

        public void setFirstname(String first_name){
            this.first_name = first_name;
        }
        public String getFirstname(){
            return first_name;
        }
        public void setLastname(String last_name){
            this.last_name = last_name;
        }
        public String getLastname(){
            return last_name;
        }
        public void setEnrollmentDate(MyDate mydate){
            this.enrollment_date = mydate.dateToString();
        }
        public String getEnrollmentDate(){
            return enrollment_date;
        }
        public void setGraduationDate(MyDate mydate){
            this.graduation_date = mydate.dateToString();
        }
        public String getGraduationDate(){
            return graduation_date;
        }
}

它無法工作,因為使用 getter 方法,您將獲得字符串形式的結果。 但是您想要擁有 MyDate。 所以改變變量的類型和方法。 所以它有效。

public void setEnrollmentDate(MyDate mydate){
     this.enrollment_date = mydate;
}

public MyDate getEnrollmentDate(){
     return enrollment_date;
} 

您可以對畢業日期執行相同的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM