I am learning Java and I have learned that methods use parentheses for passing parameters. However, I have also noticed that sometimes I see code which to me looks like a method but it does not have parentheses.
MyObject.something()
MyObject.somethingElse
Where somethingElse does not have parentheses. I assume this is similar to how an arrayList has the size method for getting its size:
myList.size()
whereas an array has length to get its size, which does not have parentheses:
myArray.length
Is my assumption correct? If not, what is the difference? This is probably an elementary question, but because of the amount of words I need to explain this problem, I have had trouble searching for it.
somethingElse
is a property (data member), not a method. No code in the class is run when you access that member, unlike with a method where code in the class is run.
Here's an example:
public class Foo {
public int bar;
public Foo() {
this.bar = 42;
}
public int getBlarg() {
// code here runs when you call this method
return 67;
}
}
If you create a Foo
object:
Foo f = new Foo();
...you can access the property bar
without parens:
System.out.println(f.bar); // "42"
...and you can call the method getBlarg
using parens:
System.out.println(f.getBlarg()); // "67"
When you call getBlarg
, the code in the getBlarg
method runs. This is fundamentally different from accessing the data member foo
.