Thread: Some Java help
View Single Post
02-09-2009   #2 (permalink)
Dragonfly
/gg FTW! Moogler
Dragonfly's Avatar
 
Join Date: Jan 2008
Location: Near a lilly pad
Posts: 142
iTrader: (0)
Dragonfly is on a distinguished road
Send a message via AIM to Dragonfly
IGN: Dragonfly
Class: Tia
Level: 67
Guild: Fusion
Default

So basically that is in a class. When you instantiate this class in a main class or something, for example:

Rectangle box = new Rectangle();

The first half of this code will make a class named box with the methods of Rectangle. The part after the equal sign will call upon that first method, setting the storedLength and storedWidth to 1.

But what if you want it to start off with other numbers other than 1? This is what the other constructor is for. If you want to make the default values different than 1, then you can use the following:

Rectangle box = new Rectangle(61.22, 21);

This will give this box to have a storedLength of 61.22 and storedWidth of 21.

It is good to have many constructors if there are many different scenarios you want to start off on. It is called an overloaded constructor because there are several constructors with the same name but have different parameters. Although to humans the constructors' name look alike, to a computer it looks like the two constructors are totally different. The method name is not just the name itself but the parameters as well. So it is legal to code the following:

Quote:
public Rectangle() {
storedLength = 1;
storedWidth = 1;
}

public Rectangle(double length, double width) {
storedLength = length;
storedWidth = width;
}

public Rectangle(double length, double width, String name) {
storedLength = length;
storedWidth = width;
}

public Rectangle(double length, String name, double width) {
storedLength = length;
storedWidth = width;
}

public Rectangle(double length, int width) {
storedLength = length;
storedWidth = width;
}
Even though the names are the same, the compiler will look at the parameter as well. Even the number of parameters can be the same if the primitive types are different. Even the order of the primitive types matter. Depending on what you put in the parameter when you instantiate this class will determine which method will execute.

Hope this helps. If you have any other questions, ask away. I love java. :3
__________________
Dragonfly - Level 6x Tia Sig Made by Synlight

Last edited by Dragonfly; 02-09-2009 at 05:05 PM.