Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 help with simple program: USING constructor method
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
rated




PostPosted: 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
Sponsor
sponsor
wtd




PostPosted: Mon Oct 13, 2008 12:48 pm   Post subject: RE:help with simple program: USING constructor method

http://wiki.compsci.ca/index.php?title=Introduction_To_Java#Classes_with_State
rated




PostPosted: Tue Oct 14, 2008 3:09 pm   Post subject: RE:help with simple program: USING constructor method

thanks but I still dont understand
Euphoracle




PostPosted: Tue Oct 14, 2008 3:33 pm   Post subject: RE:help with simple program: USING constructor method

...Did you read it?
jbking




PostPosted: 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.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: