In a class, you can create fields within them, as int bar in the following example.
Class foo{
int bar;
foo(int bar){
bar = bar;
}
int getBar() {
return bar;
}
void setBar(int bar) {
bar = bar;
}
}
-
Every time I create a new foo object in another class, will that particular object (instance of foo) have a bar property that when changed with the setBar(), only impacts that instance and no other instances?
-
I often see people create getters and setters for properties like bar in the above example. If I feel lazy and I’m just writing code for myself/fun, can I just modify the bar property of any instance of this class by accessing the property
FooInstance1.bar = 22;instead of having to write a setter and it will have the same effect as in question 1 (just the instance is changed)? -
How does the Java compiler know what method is a constructor? By the fact that it has the same name as the class? Or by the fact that one does not specify a return value in the function header? Perhaps it doesn’t even matter what the compiler thinks is a constructor (no syntactic difference between regular function), it could be just a semantic thing that people use to differentiate the meaning of functions.
EDIT: I’m having a hard time selecting a best answer. I learned something new from everyone. Thanks!
publicmakes it susceptible to unintentional writes or unprivileged reads.mainmethod has a signature ofmain(String[]). Constructors are identified by them having the same case-sensitive name as the class.As an aside, you may want to use
this.bar = barinstead, or rename your incoming parameter entirely. Inside of the constructor, the scope of thebarvariable is local to what was passed in, so your instance levelbarhasn’t been assigned.