0

I'm new to programming and also new to Java. What i'm trying right now is using a parameterized constructor, and then use the created objects with a specific method. This is the code i have:

public class Car {
int fuelcap;
int mpg;

Car(int f, int m) {      //here
    fuelcap = f;         //and here
    mpg = m;             //and here
}

int range() {
    return mpg * fuelcap;
}

public static void main(String[] args) {
    Car sedan = new Car(16, 21);
    Car sportscar = new Car(14, 16);
    System.out.println(sedan.range());
    System.out.println(sportscar.range());

}

}

The problem is, i don't know why the parameters of the constructor Car - 'int f' and 'int m' are different from the fields: 'int fuelcap;' 'int mpg;'. Can't we just create are constructor like this:

Car(int fuelcap, int mpg){
}

and then just pass values to those parameters when creating the objects?

1
  • If you assign to the field twice, it's just like assigning to a variable twice - the value after the last assignment executes will be the second assignment. Commented Jun 14, 2016 at 5:21

5 Answers 5

2

No, you cannot. You must assign the constructor parameters to the class fields in the body of your constructor, or they will not be saved. That's just how Java works. There's nothing "magical" about the constructor parameters.

Also, observe proper style:

Car(int fulecap, int mpg) {     
    this.fuelcap = fuelcap;         
    this.mpg = mpg;            
}

If you have more fields then ctor parameters, that's just fine. Just think of the constructor as a normal method that gets called after the object is created. (That last statement is only sorta-kinda true, but will give you the correct idea for this purpose.)

Sign up to request clarification or add additional context in comments.

4 Comments

So, just to be sure i know what is happening: Car(int fulecap, int mpg) { // here fuelcap and mpg are different from the fields int fuelcap; and int mpg; this.fuelcap = fuelcap; // what we're doing here is we set the field fuelcap to our parameter fuelcap, because later, when creating methods, we can assign values only to the fields this.mpg = mpg; }
You got it. Always distinguish class fields from parameters in constructors with this.<name>, is a pedantic, but good style rule. They are different variables (If it's not TMI, there are even different opcodes in the JVM to access locals/parameters and class fields.... completely different locations / entities)
Thanks man! I think i got the way it works: 1. create fields 2. create constructors with the same parameter names as the fields(right now they don't have nothing in common) and then assign the fields to the parameters using this
actually, assign the parameters to the fields i think*
1

Yes off course you can, but in that case your constructor should look like as follows:

public Car(int fuelcap, int mpg){
 this.fuelcap = fuelcap;
 this.mpg = mpg;
}

Comments

0

You have the instance variables fuelcap and mpg but if you do the constructor you mention, they will never be assigned to anything.

You could do this to make it more readable,

int fuelcap;
int mpg;

Car(int fuelcap, int mpg) { 
    this.fuelcap = fuelcap; //this is refrencing the instance variable in the class    
    this.mpg = mpg;             
}

int range() {
    return mpg * fuelcap;
}

The constructor just doesn't recognize the way you want because it can cause errors in variables with the same names.

2 Comments

So, is this the proper way to do it - i mean, naming the parameters like the fields and then just use this. to assign the field to it?
Many people do it, makes it easier to reference later on in the class. It's all about personal preference and readability, nothing is strictly right or wrong in the way you did it before.
0

Parameterized constructor is used to provide different values to the distinct objects.

if you want to use

Car(int fuelcap, int mpg){}

you must use this keyword

so the code becomes

Car(int f, int m) {      
this.fuelcap = f;         
this.mpg = m; }

If you dont use this keyword

all objects will have the same values as in the instance variables i.e, fuelcap and mpg right now its value is 0

Comments

0

Just a few hints considering good practice:

First you should make your members private (link). Moreover, it is good style to make your objets "immutable", meaning, once they are created, they cannot change the state (link). You can achieve this by declaring your fields as final.

The Car class would then look like this:

public class Car
{
  private final int fuelcap;

  private final int mpg;


  public Car( final int fuelcap, final int mpg )
  {
    this.fuelcap = fuelcap;
    this.mpg = mpg;
  }


  public int range()
  {
    return this.mpg * this.fuelcap;
  }
}

7 Comments

public int range() { return this.mpg * this.fuelcap; // why is this. needed here? Can't we achieve the same thing with mpg * fuelcap }
@Rio You are right, it is not needed here, because those two variables are clearly identifiable to be the field variables.
@Rio You can. this. is optional, but it is a good practice. It helps document the difference between accessing variables/parameters vs. fields, so other people looking at the code will know for sure what is being accessed. This is especially true for larger methods, where many parameters and variables may exist. I find it a good code practice to always do it, and IDEs like Eclipse can be told to help enforce such a "code style", using compiler error/warning "Unqualified access to instance field".
@Andreas You mean i can set Eclipse to tell me if my code style is not proper? That's awesome! Can you tell me how to do that?
@Rio You can define "Save Actions" in Eclipse: Window -> Preferences -> Java -> Editor -> Save Actions. Now go to the tab Code Style and enable "Use final modifier where possible". So, eclipse will add the final modifier keyword where possible each time you save your code.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.