What is a constructor and could some examples be provided?
This is Java btw
Java, Constructors?
Started by
makavelimx
, Apr 22 2006 04:32 PM
3 replies to this topic
#1
Posted 22 April 2006 - 04:32 PM
#2
Posted 22 April 2006 - 06:01 PM
#3
Posted 23 April 2006 - 01:27 AM
wow, its crystal clear now
Thx for the link PSGirl, I appreciate it
Thx for the link PSGirl, I appreciate it
#4
Posted 22 April 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...
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...
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users