help with simple program: USING constructor method
Author |
Message |
rated
|
Posted: Mon Oct 13, 2008 12:38 pm Post subject: help with simple program: USING constructor method |
|
|
Hi, i created a class called student for my program with the following fields: id number, credits earned, gpa, and points earned (GPA multiplied by credits). How do i create a constructor method that initializes the id number to 1234 and the gpa to 4.
This is what I have so far...sorry I dont know how to display this as java code
public class student {
int credits;
int idnumber;
int gpa;
void setidnumber (int s){
idnumber=s;
}
int getidnumber (){
return idnumber;
}
void setcredits (int i){
credits=i;
}
int getcredits (){
return credits;
}
void setgpa (int a){
gpa=a;
}
int getgpa (){
return gpa;
}
public int points(){
return (credits*gpa);
}
} |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
wtd
|
|
|
|
 |
rated
|
Posted: Tue Oct 14, 2008 3:09 pm Post subject: RE:help with simple program: USING constructor method |
|
|
thanks but I still dont understand |
|
|
|
|
 |
Euphoracle

|
Posted: Tue Oct 14, 2008 3:33 pm Post subject: RE:help with simple program: USING constructor method |
|
|
...Did you read it? |
|
|
|
|
 |
jbking
|
Posted: Tue Oct 14, 2008 4:05 pm Post subject: Constructors can be used in different ways..... |
|
|
What part don't you understand? Generally, a constructor is just the name of the class with whatever parameters you want to initially set as the values.
In your case, I could see 2 solutions to the problem:
Hard code those values in:
code: | public student() {
idnumber=1234
gpa = 4
} |
Or pass them in:
code: | public student(int iId, int iGpa) {
idnnumber = iId;
gpa = iGpa;
} |
Either way should work though you could put both methods into the class as the different parameters can ensure the proper constructor gets called when you instantiate the class with an object or type student. |
|
|
|
|
 |
|
|