I have a Main.java and in the main method I have the following code:
totalSalaries = 14000;
System.out.printf("The total payout should be %s%n", currencyInstance.format(totalSalaries));
I tried to run the above statement in debug mode to understand the traversal of how the format method gets called.
When you step-in the above format method, it inturn calls the below format method which belongs to NumberFormat class (where NumberFormat extends Format)
public final String format(long number) {
return format(number, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}
Upon then, clicking on the format method above (of NumberFormat class) within this return block, it seems to land on the below which is part of the DecimalFormat class (where DecimalFormat extends NumberFormat).
@Override
public StringBuffer format(long number, StringBuffer result,
FieldPosition fieldPosition) {
fieldPosition.setBeginIndex(0);
fieldPosition.setEndIndex(0);
return format(number, result, fieldPosition.getFieldDelegate());
}
Could someone kindly explain why the NumberFormat class is calling format method of it's subclass DecimalFormat? It shouldn't be possible isn't it ? Thanks for your help
The first thing to observe is that NumberFormat
is an abstract class:
public abstract class
NumberFormat
That means that when you call NumberFormat.getCurrencyInstance();
what you will get is an instance of a concrete subclass of NumberFormat
- in most cases that will probably be a DecimalFormat
instance.
The format(long number)
method in NumberFormat
is
public final String format(long number) {
return format(number, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}
And it calls the method format(long number, StringBuffer toAppendTo, FieldPosition pos)
which in NumberFormat
is declared as abstract method:
public abstract StringBuffer format(long number,
StringBuffer toAppendTo,
FieldPosition pos);
For a class to be instanciable it must not have any abstract methods - if it extends an abstract base class, it must implement all the abstract methods of its parent class. And if you look at the implementation of DecimalFormat
it implements that method:
public StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition) { fieldPosition.setBeginIndex(0); fieldPosition.setEndIndex(0); return format(number, result, fieldPosition.getFieldDelegate()); }
What you see in the debugger (that it steps through the format
method in NumberFormat
and then calls the format
method in DecimalFormat
) is due to the fact the method format(long number)
is declared in the NumberFormat
class. The currencyInstance is however always a DecimalFormat
instance.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments