2

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.

4 Answers 4

10

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

Sign up to request clarification or add additional context in comments.

3 Comments

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 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?"
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.
4

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.

Comments

3

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.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.