从另一个类(作业)的访问器中的另一个类调用方法

时间:2019-02-08 15:17:15

标签: java

我很难解决这个问题,也很难在网上寻找解决方案。您如何在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;
        }
}

1 个答案:

答案 0 :(得分:0)

它不起作用,因为使用getter方法,您将结果作为字符串获取。但是您想拥有MyDate。因此,请更改变量的类型和方法。这样就可以了。

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

public MyDate getEnrollmentDate(){
     return enrollment_date;
} 

您可以为毕业日期做同样的事情。