+ 2

What's the difference in properties and methods in java?

eg. for an array of strings we use "length" as a property. but for a string we use "length()" as a method plz, correct me if I'm confusing both these terms thank-you.

3rd Jun 2017, 4:49 PM
Mahesh Dudhnale
Mahesh Dudhnale - avatar
5 Respuestas
+ 3
Here are the definitions in case you don't know what they mean: Method: "A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilising the method's name" Property: "A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method" length() is a method. So in the String class, it is written something like this: class String extends Object{ private final int length = X; public int length(){ return this.length; } } So in order to call this method you need the String object, then you write: myString.length(); Just like how you do the length of anything else. This is because the length is private, you can't access it. So you cannot do: myString.length Instead, you have to call the public getter, not the variable. However, for the array, you are not calling a method. In Java, somewhere in the array class they have a variable called 'length'. However, there is no method in the array class called "getLength" or "Length". So, you don't need parenthesis since you are not calling a method. Instead, the class probably looks something like this: class A<T> implements Cloneable, java.io.Serializable{ public final int length = X; // etc } Notice the length is public. This means you can access it directly from another class. So, to access this int you just do: myArray.length; No need for parenthesis, since you are calling a variable. Why do you need parenthesis to call a method? Because methods have parameters, and these parameters can take values. When the parenthesis is empty you are saying that you are not passing any values into the parameters of the method, or the method doesn't accept anything in its parameters. I'm not sure why the creators of the language decided to use a public variable for arrays, but they did nevertheless. It could come down to how they set the value, I don't really know.
3rd Jun 2017, 5:14 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
@Rrestoring faith what a vivid explanation and @mahesh you don't tick his answer as the best
7th Jun 2017, 2:59 PM
Vaibhav Sharma
Vaibhav Sharma - avatar
+ 1
@Rrestoring faith, thanks for the answer. reading this answer introduced me to interfaces and genetics. thank-you!
3rd Jun 2017, 5:22 PM
Mahesh Dudhnale
Mahesh Dudhnale - avatar
+ 1
oh, I'm new to sololearn.
7th Jun 2017, 3:27 PM
Mahesh Dudhnale
Mahesh Dudhnale - avatar
0
*generics, autocorrect
4th Jun 2017, 7:21 AM
Mahesh Dudhnale
Mahesh Dudhnale - avatar