Help - Search - Members - Calendar
Full Version: Java, Constructors?
Pixel2Life Forum > Help Section > Desktop Programming
makavelimx
What is a constructor and could some examples be provided?

This is Java btw
PSgirl
I've found a website where it's very well explained:
http://www.leepoint.net/notes-java/oop/con...onstructor.html
makavelimx
wow, its crystal clear now

Thx for the link PSGirl, I appreciate it
tjl30
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...
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.