0

AtomicInteger class has 2 methods, get() and intValue() with following definitions.

intValue() definition :

/**
 * Returns the value of this {@code AtomicInteger} as an {@code int}.
 */
public int intValue() {
    return get();
}

get() definition:

/**
 * Gets the current value.
 *
 * @return the current value
 */
public final int get() {
    return value;
}

Is there any advantage of having a non final method intValue()? For all practical purposes, we can use get method if I am not wrong. Please explain if there is any advantage for such practice.

joc
  • 1,336
  • 12
  • 31
Sreekanth Karumanaghat
  • 3,383
  • 6
  • 44
  • 72
  • 1
    The code will be more readable when you see `intValue()` instead of `get`. – xenteros Aug 29 '16 at 09:46
  • 1
    The method `intValue()` probably exists for uniformity with class `java.lang.Integer` which also has an `intValue()` method. – Jesper Aug 29 '16 at 09:50
  • 3
    The method `intValue()` exists because `AtomicInteger` extends `Number`, where it is abstract. – user207421 Aug 29 '16 at 09:51
  • @EJP darn, this is the answer I believe; I was about to write it, but then you came up with it first. Make that an answer :p – fge Aug 29 '16 at 09:52
  • @xenteros. Another point that I want to note here is that a method name usually starts with "verb" but "intValue" has violated that convention. Just because you mentioned readability here. – Sreekanth Karumanaghat Aug 29 '16 at 10:26

1 Answers1

5

The method intValue() exists because AtomicInteger extends Number, where it is abstract.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Then what is the use of get(). Can' t the definition of intValue() just be "return value;" – Sreekanth Karumanaghat Aug 29 '16 at 10:05
  • @SreekanthKarumanaghat Certainly. If you want to know why they added `get()` you would have to ask the authors. – user207421 Aug 29 '16 at 10:06
  • There has to be a reason for everything, I can't get everything from horse's mouth, I believe that is one of the reasons why this site exists :) – Sreekanth Karumanaghat Aug 29 '16 at 10:08
  • All that I meant is that is there any significant advantage of defining another method that is final rather and calling it from intValue, rather than just implementing that definition inside the intValue itself. If yes, what? – Sreekanth Karumanaghat Aug 29 '16 at 10:10
  • 1
    Whatever the reason may be, if any, it is hidden in the minds of the authors, unless it is (a) stated in the documentation (b) implied by the formal specification or (c) explained by an author posting here. The answer to your second comment is 'no'. – user207421 Aug 29 '16 at 10:11
  • 1
    All the atomic types have a `get` method, including the ones that don't have a logical analog to `intValue()`. It's just for consistency with the other atomics as well as the `Number` type. – Louis Wasserman Aug 29 '16 at 19:15