Java调度导致错误

时间:2014-09-09 01:37:20

标签: java

此代码应该从我的课程中获取变量。

    public void prettyPrint(){
        Course myCourse = new Course(myCourse.n, myCourse.days, myCourse.start, myCourse.end);


        for (int i=0; i>Courses.size();i++){
            System.out.println("---"+ Course.dayString + ' '+ ' '+" ---");
            System.out.println(myCourse.start +"-"+ myCourse.end+ ": " + myCourse.n );
        }

这让我误以为“myCourse.n可能没有被初始化”。如果他们只是从课程类中提取信息,我如何初始化它们?

2 个答案:

答案 0 :(得分:1)

Course myCourse = new Course(myCourse.n, myCourse.days, myCourse.start, myCourse.end); // myCourse只是一个参考,当您调用new时,myCourse尚未初始化。


也许你应该像这样编码:

Course myCourse = new Course(n, days, start, end);

答案 1 :(得分:0)

在创建对象之前,不能引用对象中的值。但是,您可以创建静态类变​​量并引用它们,而无需创建任何对象,如下所示:

class Course{
    static int n = 1;
    static int days = 180;
    //..other definitions
    //..
}

class Main{
    public static void main(){
      Course myCourse = new Course(Course.n, Course.days);
    }
}

但是,静态变量会在实例变量之间引入依赖关系。更好的设计是factory design pattern,其示例实现如下:

class Course{
    int n;
    int days;
    // other instance definitions

    public course(int n, int days){
         this.n = n;
          this.days = days;
     }
}

class History extends Course{
     public History(){
          super(10,200);//the values that you want this course to have
     }
}

class Geography extends Course{
     public Geography(){
          super(20,100);//the values that you want this course to have
     }
}

class Main{
     public static void main(String args[]){
          Course history = new History();
          Course geography = new Geography();
     }
}