|
JavaFAQ Home » Java IAQ by Peter Norvig

Answer:
Short answer: no. Get used to writing the class name to access static
methods from outside the class. However, if you insist on a longer answer
...
|
If you only want a few methods, you can put in calls to
them within your own class:
|
public static double sin(double x) { return Math.sin(x); }
public static double cos(double x) { return Math.cos(x); }
...
sin(x)
| |
Static methods take a target (thing to the left of the dot) that is either
a class name, or is an object whose value is ignored, but must be
declared to be of the right class. So you could save three characters per call by
doing:
|
// Can't instantiate Math, so it must be null.
Math m = null;
...
m.sin(x)
| |
java.lang.Math is a final class, so you can't inherit from it, but if you
have your own set of static methods that you would like to share among
many of your own classes, then you can package them up and inherit them:
|
public abstract class MyStaticMethods {
public static double mysin(double x) { ... }
}
public class MyClass1 extends MyStaticMethods {
...
mysin(x)
}
| Peter van der Linden,
author of Just Java, recommends against both of the last two
practices in
his FAQ. I agree
with him that Math m = null is a bad idea in most cases, but
I'm not convinced that the MyStaticMethods demonstrates
"very poor OOP style to use inheritance to obtain a trivial name
abbreviation (rather than to express a type hierarchy)." First of
all, trivial is in the eye of the beholder; the abbreviation may be
substantial. (See an
example of how I used this approach to what I thought was good
effect.) Second, it is rather presumptuous to say that this is very
bad OOP style. You could make a case that it is bad Java
style, but in languages with multiple inheritance, this idiom would be
more acceptable.
Another way of looking at it is that features of Java (and any
language) necessarily involve trade-offs, and conflate many issues. I
agree it is bad to use inheritance in such a way that you mislead the
user into thinking that MyClass1 is inheriting behavior from
MyStaticMethods, and it is bad to prohibit MyClass1
from extending whatever other class it really wants to extend. But in
Java the class is also the unit of encapsulation, compilation
(mostly), and name scope. The MyStaticMethod approach scores
negative points on the type hierarchy front, but positive points on
the name scope front. If you say that the type hierarchy view is more
important, I won't argue with you. But I will argue if you think of a
class as doing only one thing, rather than many things at once, and if
you think of style guides as absolute rather than as trade-offs.
This tip is reprinted on JavaFAQ.nu by by courtesy of
Peter Norvig I am
thankful for his important contributions to my site - 21 Infrequently Answered
Java Questions. Alexandre Patchine
Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|