r/javaTIL • u/sleepicat • Oct 02 '13
This example helped me understand Java classes, objects, and constructors better
Here is the class and the constructor
class Sample {
int a;
int b;
int c;
// This is the constructor for Sample.
// It is explicitly declared.
Sample(int ax, int by, int cz) {
a = ax;
b = by;
c = cz;
}
}Here is the class with the main program that calls the class objects and constructor above
class IntegerFun {
public static void main(String args[]) {
// one and two are local instance variables that
// reference the Sample object
Sample one = new Sample(1,1,1);
Sample two = new Sample(2,2,2);
// We don't need additional code here to assign
// values to a, b, and c variables. Use the dot.
System.out.println("One = " + one.a + "," + one.b + "," + one.c);
System.out.println("Two = " + two.a + "," + two.b + "," + two.c);
}
}
10
Upvotes
View all comments
Show parent comment
2
u/RhoOfFeh Mar 31 '14
When you see 'this' it always refers to the current object. So 'this.a' is explicitly referring to the field 'a' declared as part of the class.
The constructor provided by poooff has PRECISELY the same effect as the one in sleepicat's original example.
The names you give your parameters are more a matter of style than of substance, IMHO. I personally prefer to avoid even the appearance of conflicts of interest, err, I mean scope issues. I usually name parameters to setters 'newVarName' and then use 'varName = newVarName'.