Thursday, August 26, 2010

NumberFormat is an abstract class

Courtesy of Sun Web Learning Center



Given:

12.   NumberFormat n = new NumberFormat();
13.   n.setMaximumFractionDigits(2);
14.   System.out.println((String) n.format(765.4321));

What is the result?

A 765.43
B 65.4321
C 765.4321
D Compilation fails.
E An exception is thrown at runtime.

D is correct. Compilation fails because NumberFormat is abstract. You must use the getInstance method to get a NumberFormat instance.

Correct code would be


12.   NumberFormat n = NumberFormat.getInstance();
13.   n.setMaximumFractionDigits(2);
14.   System.out.println((String) n.format(765.4321));

Notice that "new" has been removed on line 12 because NumberFormat is abstract class, not an actual class.

No comments:

Post a Comment