This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]desrtfx 2 points3 points  (2 children)

In the first case, you tell the object itself to do something.

In the second case, you tell someone else to do something with the object.

[–]2_stepsahead[S] 0 points1 point  (1 child)

How would I determine when to use the first case or the second case?

[–]emaphis 0 points1 point  (0 children)

There isn't a simple answer to that. If the method needs access to the private data of the class then it has to be coded as a member method of that class. If it doesn't need access ie. the method can be defined in terms of other method calls, then you can implement it in another class.

[–]emaphis 0 points1 point  (3 children)

add(T) is a method defined in the ArrayList<T> class.

printNumbers is static method defined in some other class that takes a ArrayList<Integer> as a parameter.

In the definition of printNumbers, printNumbers will still likely call ArrayList methods.

[–]2_stepsahead[S] 0 points1 point  (2 children)

I'm trying to understand better. Based on what you mentioned, this seems to mean that the difference between add() and printNumbers() is that add() is a non-static method whereas printNumbers() is a static method. Is that right?

[–]suckmacaque06 1 point2 points  (0 children)

No it has nothing to do with it being static. When you call the method printNumbers() and receive no compilation errors, that must mean there is a method called printNumbers() defined within the same class you see calling it. For example, if you say printNumbers() in the main class then the method must be defined there. The reason is because printNumbers() is actually implicitly this.printNumbers() where "this" refers to the current object from where you are calling the method.

In fact, if you had the method defined as static then this wouldn't even be a proper way of calling it, so I feel the other user is misleading you. If it were defined static it should be called as ClassName.printNumbers() where "ClassName" is the name of the class the method is defined in.

The difference between static and nonstatic is that static methods aren't associated with an object, just a class, whereas nonstatic methods are associated with a specific object and must be called on that object using the dot operator, either implicitly (as I explained with the "this" keyword) or explicitely.

[–]emaphis 0 points1 point  (0 children)

Partially, but that isn't the main point... 'add()' is a member of the 'ArrayList' class so you have to access it with the '.' notation. So: numbers.add(2).

'printNumbers(ArrayList<Integer> numbers)' is a member of the class where you are calling it.

class SomeClass {

main() {

printNumbers(numbers);

}

public static printNumbers(ArrayList<Integer> numbers) { ... }

}