Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No parentheses in java

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.

like image 976
Chronicle Avatar asked Apr 16 '26 20:04

Chronicle


2 Answers

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.

like image 78
T.J. Crowder Avatar answered Apr 18 '26 08:04

T.J. Crowder


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.

like image 42
solvator Avatar answered Apr 18 '26 09:04

solvator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!