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
.
myList.size()
call a method defined in list class (public defined)
myArray.length
call a property in array class not method
public class MyClass{
public int length;
public int size(){
....
}
}
MyClass mc =new MyClass();
mc.length;
mc.size();
it is a class field which isn't a private
field (usually it can be protected
, package
or public
), so you can take it straight from your class. Usually fields are private, so you cannot take it like this outside your class definition.
This is triggering method called something of the instantiated object called someObject.
someObject.something();
This is accessing a property of the object called someObject (property which is public, most probably).
someObject.name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.