OK, let's focus on a function first.
Let's say I wanted to write a function that would sum two numbers. Easy enough. Following the basic steps, I get this function:
- public int getSum() {
-
return 1 + 2;
-
}
That's kind of lame. It always returns 3. If I want it to return some other sum, I'd have to change the code itself. Instead, I'll make it use variables that are passed as arguments:
- public int getSum(int first, int second) {
-
return first + second;
-
}
Now I want to use this in my main function. So I'll do this:
- public void static main(String[] args) {
-
int myVar = getSum(10, 20);
-
int a = 5, b = 15;
-
int mySum = getSum(a, b);
-
}
The first time, I call it using two hard-coded numbers. The second time, I call it with two int variables I made. So that's you you can write a multi-argument function.
A Constructor for a class is like a starter method that gets everything ready so that the object can be used. For instance, if you make a new Car, there are a few things that need to be done before it can be ready to be driven.
1) It needs gas.
2) It needs wheels.
3) It needs a model number and name.
4) It needs an owner.
A constructor sets all these things up. Now, if this were code, the constructor might look like this:
- public Car() { // Note there is no return type here. Constructors never have a return type, and their name is always the same as a class.
-
gas = 20; // 20 gallons of gas.
-
frontLeftWheel = new Wheel();
-
frontRightWheel = new Wheel();
-
backLeftWheel = new Wheel();
-
backRightWheel = new Wheel();
-
modelName = "Ford Taurus";
-
modelNumber = 12345;
-
owner = new Person();
-
}
This constructor sets all it's variables to starting values so that the Car can be used. But it always sets it to the same things. What if we want different cars each time? To do that, we make the constructor accept arguments, just like any other function:
- public Car(int startingGas, String name, int num, Person driver) {
-
gas = startingGas;
-
frontLeftWheel = new Wheel();
-
frontRightWheel = new Wheel();
-
backLeftWheel = new Wheel();
-
backRightWheel = new Wheel();
-
modelName = name;
-
modelNumber = num;
-
owner = driver;
-
}
Note how we used the arguments to set up the car. So now, if I want to create a Dodge Caravan, model number 31416 and 12 gallons of gas, I'd write:
- Person Ganon11 = new Person();
-
Car ganonsCar = new Car(12, "Dodge Caravan", 31416, Ganon11);
and now ganonsCar has all the attributes I wanted it to have.
With this as a guide, can you write your constructor and methods?