makavelimx
Apr 22 2006, 04:32 PM
What is a constructor and could some examples be provided?
This is Java btw
PSgirl
Apr 22 2006, 06:01 PM
makavelimx
Apr 23 2006, 01:27 AM
wow, its crystal clear now
Thx for the link PSGirl, I appreciate it
tjl30
Apr 22 2007, 12:29 PM
So different classes have different functionality, to instantiate a class you use the classes constructor. For example if you wanted to make an adding class then maybe it would look like this
public class addingClass {
private int number1;
private int number2;
public addingClass(int num1, int num2){
number1 = num1; //What is being done here is the number that the client inputs is set to a private instance variable
number2 = num2;
}
public int add(){
return number1 + number2;
}
}
Then in the client code, weather it be a GUI, a command line, ect. the client can set waht the numbers are going to be by constructing an adding object.
addingClass add1 = new addingClass(1, 2); //constructs a variable of type addingClass using the addingClass' constructor
I hope that gives you an idea of what a constructor is used for, or maybe this will just confuse you...