Reputation: 1221
This code is supposed to fetch the variables from my class Course.
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 );
}
This gets me errors that say "myCourse.n may not be initalized." How do I initialize them if they are just pulling the info from the Course class?
Upvotes: 0
Views: 45
Reputation: 552
You cannot reference values in an object before creating it. However, you can create static class variables and reference them without creating any objects as shown:
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);
}
}
However, static variables introduce dependency between instance variables. A better design would be the factory design pattern with a sample implementation as follows:
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();
}
}
Upvotes: 0
Reputation: 91
Course myCourse = new Course(myCourse.n, myCourse.days, myCourse.start, myCourse.end);
// myCourse is just a reference, when you call new , myCourse hasn't been initialized.
Maybe you should code like this:
Course myCourse = new Course(n, days, start, end);
Upvotes: 1