The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

How to perform operations on arguments with type OBJECT?

Hello guys
I'm a Java beginner. I just learned class access controls and whatnot, and I wanted to make a class that I called "Calculus" that has different methods for calculus (addition, multiplication etc). I want the arguments of my methods to handle any type, so I have to use Object (no?). With this, i cannot perform any operation on the arguments. here is an example :

Re: How to perform operations on arguments with type OBJECT?

If it is just a mathematical operation, define the method parameters as primitives which can be used directly for mathematical operations. Alternatively, you could pass something like a Number object, using the get* methods to retrieve a primitive value
See http://download.oracle.com/javase/tu...datatypes.html

From what I understand, I have to import the Number library using "import java.lang.Number;" and then 'convert' the arguments of my method to primitive values?
How would I know if it's an integer that is passed or it's a float? Is there any solution that works regardless of the argument type?

Re: How to perform operations on arguments with type OBJECT?

java.lang is a default import so there is not need to explicitly import (give it a try and see). Your methods should define what they accept and the precision they require. If you need floating point math, then define the method as floating point - don't rely on clients (the caller) specifying that behavior - it should be specified in the class you posted.

Re: How to perform operations on arguments with type OBJECT?

So I should figure out the type of the argument first and change it accordingly and work on it? because, for example, if the client passes it with an integer, i don't want to change it to anything else. i want to perform the operation without changing the arugment's type.
I'm sorry for my slow understanding, i'm just trying to get a clearer picture :p

Re: How to perform operations on arguments with type OBJECT?

A good example of the overloading Norm suggests is demonstrate in Math (Java Platform SE 6)
For example, the abs/min/max methods have several methods which accept different primitives but accomplish the same task