views:

133

answers:

4

Is it possible to extend the Math class and still use the Math class to call the extended method?

For example, I have a method public static double mean (LinkedList<? extends Number) I would like to call like this Math.mean(list). Is this doable? How?

Thanks.

+11  A: 

Doc Java.lang.Math is Final class, can't be extended
Update: Static Method can't be inherited & final class can't be extended.

org.life.java
This is not terribly relevent. If Math **wasn't** final, the OP still couldn't do what he wanted *because the methods are static*.
Kirk Woll
@Kirk Woll Yes you are right, but the main thing is "is it Possible to extend the Math class and still use the Math class to call the extended method?"
org.life.java
It's as relevant as the fact the methods are static. If Math methods **weren't** static, the OP still couldn't do what he wanted *because the class is final.*
AHungerArtist
+3  A: 

You can't subclass the Math class because it's final. You could use composition i.e. write your own wrapper class but there wouldn't be much point in that because all of Math's methods are static.

John Topley
+4  A: 

Even if Math wasn't final, you couldn't do this. You can't use a superclass to call a function defined in a subclass. By definition, a subclass has access to all non-private methods defined in the superclass, but a superclass does not have access to functions in a subclass.

Jay
Thanks for your explanation. That was helpful too.
nunos
+1  A: 

A workaround could be to create your own Math class and use java.lang.Math as composite. The methods without any change can just be delegated to original methods in java.lang.Math. You could rewrite the methods you want to change or expose new methods in your Math class.

The code look like:


public class YourMath {  
  public static double mean(LinkedList) {
     //Your new method
  }
  public static double abs(double a) {
     return Math.abs(a); //Delegate
  }
  //...... Any other methods
}
Sheng Chien