Question:
question about writing very basic class constructors in the java programming language?
2009-11-08 19:46:03 UTC
below i have written 2 versions of an example class "Person", each with 1 constructor method and a member variable called age, representing the age of the Person.

the constructor has a parameter which is to be assigned to the member variable in the simple fasion: memberVariable=parameter;

the difference between these two examples is in how the parameter is assigned to the member variable. One uses the "this" function, and the other uses different variable names for the parameter and the member variable.

My question is: which of these examples is correct? If they both would work, then which one is better programming?



class Person{
public Person(int age){
this.age = age;
}

private int age;
}



class Person{
public Person(int inputAge){
age = inputAge;
}

private int age;
}
Three answers:
Mark aka jack573
2009-11-12 18:14:11 UTC
They are both the same.



The difference in the parameter names is that the second one does not use the name of the variable in the class.



It is usually better if you can make a parameter name that is different to the variable name, like in the second one. But if you cannot think of a better name, and sometimes you cannot, then you use the first one.



As to which is better programming, it does not really matter. Create a style for doing something and continue doing the style.



If you go to work for someone, they may have a way to do it. It could be the first or the second. So if they have a 'standard', you will have to do it the way they say.



Same thing if you are doing assignments. If your instructor says to do it 1 way or the other, then you should do that.



If you can choose, just choose the one you are most comfortable with and use that.



Hope that helps you out.
2009-11-08 20:28:37 UTC
Both are same. just the variable name is different. But the first one is a good programming practice to use this.age because it clearly says use member variable age.
mehan
2016-10-16 09:49:19 UTC
public classification Bulb(){ deepest boolean state; public Bulb(){ state = fake; } public void turnOn(){ state = genuine; } public void turnOff(){ state = fake; } public void changeState(boolean state){ this.state = fake; } } public classification workingClass(){ public void run(){ Bulb bulb1 = Bulb(); Bulb bulb2 = Bulb(); bulb1.turnOn(); bulb2.turnOff(); } }


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...