views:

787

answers:

12
+1  Q: 

Java Constructors

I am trying to learn how to specify class constructors in Java. I am starting to understand that they specify the types of instance variables of objects made from that class. They also can be used to set the instance variable initial values. The follow example is from the Java tutorial on Sun's website:

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

Where in your classes source code should you put the constructor(s)?

Are these arguments the names of the variables?: (int startCadence, int startSpeed, int startGear) or are gear, cadence and speed the names of the variables?

What is the difference between (int startCadence, int startSpeed, int startGear) and gear, cadence and speed?

In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.

+2  A: 

You really need a copy of Head First Java

Fortyrunner
@Offensive vote: This is not really offensive, just don't quite useful.
OscarRyz
+2  A: 
  1. It's totally up to you. I usually start with all variables, then constructors, then methods, but it's just personal preference.
  2. The names of the arguments are completely irrelevant, as long as you don't name them the same thing as your variables. In this example, gear, cadence, and speed are the variables.
  3. You are (or somebody is) passing three ints to the constructor. The names (startCadence, startSpeed, and startGear are called the formal parameters, and they are the way you can identify the arguments. See http://en.wikipedia.org/wiki/Parameter_(computer_science).
    gear, cadence, and speed are defined somewhere else in the class. Any method in the class can refer to them.

Don't worry--if you work at it, this sort of thing will be second nature pretty soon.

Oh, and may I suggest that you get a good IDE? BlueJ is supposed to be good for beginners, and NetBeans and Eclipse for more experienced programmers. Source code highlighting can be invaluable.

Michael Myers
Thank you for the encouragement.
Patrick Cassell
My college instructor encourages us to use the jGRASP IDE developed at Auburn University. I also have the three you mentioned, but have not used those as much as jGRASP.
Patrick Cassell
I have never tried jGRASP and have no idea how it compares, but anything is better than Notepad. :)
Michael Myers
+1  A: 

I generally put my constructors up near the top of my file, after package, import, Javadoc, and static/instance variable declaration sections.

gear, cadence, and speed are the class variables, presumably defined outside of the constructor somewhere. startCadence, startSpeed, and startGear are also variables, but they are the parameters passed to the constructor.

You may also see something like this:

public Bicycle(int cadence, int speed, int gear) {
    this.gear = gear;
    this.cadence = cadence;
    this.speed = speed;
}

which sets the class variables from the parameters of the same name.

R. Bemrose
+5  A: 

gear, cadence and speed are member variables of the class (declared elsewhere) and startCadence, startSpeed, and startGear are function parameters.

class Bicycle
{
    private int gear, cadence, speed;

    public Bicycle(int startCadence, int startSpeed, int startGear)
    {
        // set the value of member variables from passed parameters
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;

    }
}
basszero
+6  A: 

The constructors can appear anywhere in the code for the class. However, by convention, most people put them before any other functions that aren't constructors.

As for the variable names, all 6 are actually variable names, but the scope is differnet. The ones specified as parameters to the constructor (startCadence, startSpeed, startGear) are only available within the constructor. The other 3 (gear, cadence, speed) are probably class-wide variables, available to all methods. However the definition isn't shown in your code snippet. The full class would look mroe like:

class Bicycle
{
    // class-level variables
    private int gear;
    private int cadence;
    private int speed;

    // constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }

    // another method (not a constructor)
    public void ShiftUp() {
        gear = gear + 1; // notice the 'gear' variable is available here too.
    }
}

Hope that helps!

rally25rs
A: 

Actually, the arguments to a constructor don't have to stored as the object's member variables. Here's an example:

class NumberAsString {

   private String numAsStr;

   public NumberAsString(double number) {
      this.numAsStr = Double.toString(number);
   }

}

In this example, the constructor argument isn't actually stored anywhere, but its value is necessary for the calculation of one or more member variable values.

The behavior you've seen, where all the arguments are stored directly as member variables, is pretty common. Especially for certain kinds of classes that simply provide "getter" and "setter" methods for their member variables (without offering any calculation or transformation functions). In the java world, these kinds of classes are commonly referred to as "beans". (Which, yes, is a very stupid name.)

benjismith
A: 

The basic difference between int startCadence and cadence is not in the variables, but in their scope. If a variable is defined inside a method, like a constructor, it will only exist inside this method, but not outside. If a variable is defined in a class, it will exist everywhere in that class, such a variable has a global scope. The variable startCadence wll only exist inside the constructor, so if you want to use it's value elsewhere, you can pass it to another variable with a global scope. This is what happens here: cadence = startCadence;

Berend Vervelde
+2  A: 

Where in your classes source code should you put the constructor(s)?

I use the following:

package statement ....
import statements....


public class MyClass { 
     // instance attributes
     private int i;

     // class attribute 
     private static int MAX;

     // static methods 
     public static int getClassCount() { 
     }

     // Constructor!! 
     public MyClass() {  // constructor.
     }

     // public methods 
     // protected methods
     // private methods 

     // public static void main
 }

But they can go anywhere. I feel it is better yo put things in order of visibility. For instance I rather have the public methods before the private methods ( so if I'm looking for an specific public method I know it's at the top of the file ) For the same reason I usually put the constructor at the top.

Are these arguments the names of the variables?:

Not necessary, you can name them as you want. I usually use the same name.

...or are gear, cadence and speed the names of the variables?...

They are the instance variable names

What is the difference between (int startCadence, int startSpeed, int startGear) and gear, cadence and speed?

The first are the parameter names for the constructor and the former are the names of the attributes of the object it self.

Take this other sample:

 public class Person { 
     private String name; // a person has a name.

     public Person( String nameParameter ) {  
        this.name = nameParameter;
     }
     public String toString() { 
         return "My name is : " + this.name;
     }

     public static void main( String [] args )  { 

          // creates a new "instance" and assign "Patrick" as its name.
         Person one = new Person("Patrick");
         System.out.println( one ); // prints "My name is: Patrick"

         // each person have its own name. 
         Person two = new Person("Oscar");
         System.out.println( two ); // prints "My name is: Oscar"         


     } 
 }

As you see, when you pass a value to the constructor you're using an argument, and when you see the constructor code you see the parameter name ( which receives that argument ) and then it is assigned to the instance attribute.

OscarRyz
FYI: Above where you refer to "package statements" and "import statements", you might be interested to know that those technically aren't statements. They're called "directives". Just fyi.
benjismith
Really? :O New thing learned. :)
OscarRyz
Yep. The difference between a statement and a directive is that a statement causes runtime behavior (usually by the direct execution of machine instructions), while a directive only causes compile-time behavior. In Java, statements can only occur within method declarations, and static initializers.
benjismith
...(continued)... The "import" keyword acts as a directive because it tells the compiler to bring a class definition into the local namespace, without directly causing any runtime behavior.
benjismith
...(continued)... If you ever write a compiler, the basic list of artifacts you'll probably need to support (for an object oriented language like Java) will be: directives, declarations, statements, expressions, and operators.
benjismith
A: 

The (int startCadence, int startSpeed, int startGear) are the constructor arguments and they will set the Bicycle fields - cadence, speed, and gear. They are available only within the constructor. Gear, cadence, and speed are instance variable and they are unique for each Bicycle instance and you can reference them in other methods. The constructor arguments allow you to provide parameters for the initizlization of an object. In this example, you can create a Bicycle object with a gear of 1, cadence of 0, and a speed of 0 like this

Bicycle bike = new Bicycle(0, 0, 1);

Or if you can create a moving bicycle where the cadence is 60 rpm, and the speed is 10 mph, at 3rd gear like this

Bicycle bike = new Bicycle(60, 10, 3);

The placement of the constructor is irrelevant but usually constructors are placed in the beginning of the class definition.

A: 

Please read the tutorial thoroughly until you really understood everything.

Bombe
Not a bad idea, but not helpful.
Bill K
Actually, reading documentation and tutorials is _very_ unhelpful—unless you skip the parts that really explain things but are harder to understand.
Bombe
I did look at the tutorial on Sun's Java Site. It helped me to understand things a bit better. I thought maybe some one here could give me a less technically written explanation.
Patrick Cassell
A: 

1) The location of the constructor doesn't matter in the slightest. Going by convention, however, I would personally place it as follows:

public class Bicycle {

    public int gear, cadence speed;

    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }

    public void otherFunction1() {}
    public void otherFunction2() {}
    public void otherFunction3() {}

}

2) gear, cadence, and speed are member variables of the class; they belong to each Bicycle, and are different variables for each Bicycle. startCadence, startSpeed, and startGear, however, are local variables, which only belong in that function. When I call for a

new Bicycle(10, 15, 5);

startCadence is set to 10, startSpeed is set to 15, and startGear is set to 5. Then, the constructor initializes the member variables to their "start" corresponding variables.

Allan S
A: 

My best advice would be to find your "Beginning the Java programming language" of choice.