Beginners Question: Is overloading really needed?

N

Nard

Hi all,

I'm trying to write a library-class which contains a method for which
I don't know in advance the data types the programmer will present to
this method.

No I have implemented this as follows:
public static void Plus (int A, int B) {
return (A+B);
}
public static void Plus (int A, long B) {
return (A+B);
}
etc. for floats, doubles, int [], long [] ....

This results in a lot of methods to get all the types and
combinations.
However I can't imagine this is the easiest way.

My background is in VB6, which has a data-type called 'variant'. This
can be used when the exact datatype is not known in advance and
results in 1 method for all datatype-combinations. This opposed to
above multiple methods in java-code. Is something like VB available in
Java, or is this perhaps bad programming?

Hope you can help, thx, Nard
 
O

Oscar kind

Nard said:
I'm trying to write a library-class which contains a method for which
I don't know in advance the data types the programmer will present to
this method.

No[w] I have implemented this as follows:
public static void Plus (int A, int B) {
return (A+B);
}
public static void Plus (int A, long B) {
return (A+B);
}
etc. for floats, doubles, int [], long [] ....

This results in a lot of methods to get all the types and
combinations.
However I can't imagine this is the easiest way.

The "easiest way", and also the "best way" depend on several factors:
- Is it written once, or updated reasonably often?
- Do you mind having an overloaded method? (i.e. is the method very
complex, so overloading caused massive code duplication)
- Can you fall into the pittfall that the compiler selects another
overload that you expected (in this case I believe you won't)?
- Is efficiency an issue?


In this case, I'll assume that the end decision is that overloading is
unwanted, but YMMV.

With java 1.5, there is autoboxing. You can use this, by having one
parameter type: Number. Then, in the method, you can determine the largest
type of the two, instantiate the correct subclass of Number, and perform
the operation.

My background is in VB6, which has a data-type called 'variant'. This
can be used when the exact datatype is not known in advance and
results in 1 method for all datatype-combinations. This opposed to
above multiple methods in java-code. Is something like VB available in
Java, or is this perhaps bad programming?

There isn't AFAIK, as Java doesn't have dynamic typing. Whether this is a
good thing or not (both with respect to Java and in general) is open to at
least some debate.
 
S

Steven

Hi all,

I'm trying to write a library-class which contains a method for which
I don't know in advance the data types the programmer will present to
this method.

No I have implemented this as follows:
public static void Plus (int A, int B) {
return (A+B);
}
public static void Plus (int A, long B) {
return (A+B);
}

These should return a type, since you are adding longs I shall assume
you are returning a long.
etc. for floats, doubles, int [], long [] ....

This results in a lot of methods to get all the types and
combinations.
However I can't imagine this is the easiest way.

Ok I am at a loss why you would want to create a function to do a
basic function like Plus and will assume that you are using this
merely as a simple example.

The only thing I can think of (maybe another person will have a better
idea) is to have your function work with var args as follows: Requires
Java 5:

package test;

public class VarArgs {

public static double varArgs( double ... args )
{
double rc = 0;
for(int i=0;i<args.length;i++)
{
rc += args;
}
return rc;
}
/**
* @param args
*/
public static void main(String[] args) {
int a = 10;
long b = 35;
double c = VarArgs.varArgs(a,b);
System.out.println(c);
}

}

--Steve
 
J

John C. Bollinger

Nard said:
I'm trying to write a library-class which contains a method for which
I don't know in advance the data types the programmer will present to
this method.

Clearly you know (or can require) _something_ about the data types.
No I have implemented this as follows:
public static void Plus (int A, int B) {
return (A+B);
}
public static void Plus (int A, long B) {
return (A+B);
}
etc. for floats, doubles, int [], long [] ....

This results in a lot of methods to get all the types and
combinations.
However I can't imagine this is the easiest way.

It isn't. One very important thing to understand is that the actual
arguments to a method do not have to exactly match the formal parameters
in type:

() Arguments of primitive type are subject to "widening primitive
conversion", which basically means that you can pass an argument of a
"smaller" type where one of a "larger" type is expected. From smallest
to largest you have byte < char, short < int < long < float < double.

() Arguments of reference type (i.e. references to any kind of object,
including an array) are subject to "widening reference conversion" which
basically means you can pass an argument of a subtype where one of its
supertypes is expected.

Thus you can greatly reduce the number of argument types you need to
deal with. Moreover, you can in most cases avoid the combination
problem: in you example, for instance, it might be useful to have
Plus(int, int) and Plus(long, long) (the former returning int, the
latter long), but there is no use at all for Plus(int, long) or
Plus(long, int) -- Plus(long, long) serves that role. Indeed, the only
reason that Plus(int, int) might be useful alongside Plus(long, long) is
that you don't want to have to cast the result of the latter to int.
My background is in VB6, which has a data-type called 'variant'. This
can be used when the exact datatype is not known in advance and
results in 1 method for all datatype-combinations. This opposed to
above multiple methods in java-code. Is something like VB available in
Java, or is this perhaps bad programming?

For primitives, you can use type double if you really want to support
*every* combination of primitives with one method. Do note, however,
that with that approach there may be a loss of precision for actual
arguments of type long, and that if you are performing computations, the
floating-point arithmetic that you will end up performing is slower than
integer arithmetic.

I hope that's enough to get you going. It focuses mostly on primitive
datatypes, because that's where your question focused. Dealing with
reference types (including arrays) is largely a different question, and
for that you should start by studying object oriented programming
principles, especially "polymorphism". You should also consider that it
is *your choice* how you define the methods, and it is left to your
judgment which methods are appropriate or useful.
 
K

kaeli

Hi all,

I'm trying to write a library-class which contains a method for which
I don't know in advance the data types the programmer will present to
this method.

Sure you do.
You know that they have to be able to be added. That limits it right there to
numbers of some kind, unless you plan on using Plus for some other object
operation as well.

Read up about Factory and Builder patterns. :)
http://www.patterndepot.com/put/8/Creational_Patterns.htm

Though I assume your example was merely simplistic to showcase your point. If
it really IS this simple, other people already did this. See the post about
Jakarta. In Java, people have already done an awful lot of stuff. Always look
around for open source packages before deciding you need to make a new thing.

--
--
~kaeli~
"When dogma enters the brain, all intellectual activity
ceases" -- Robert Anton Wilson
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace
 
N

Nard

John C. Bollinger said:
Nard wrote:

() Arguments of primitive type are subject to "widening primitive
conversion", which basically means that you can pass an argument of a
"smaller" type where one of a "larger" type is expected. From smallest
to largest you have byte < char, short < int < long < float < double.

Thanks, I made the method:
public static double mathPlus(double A, double B) {
return (A+B);
}
And this works fine, also for ints, longs etc!
() Arguments of reference type (i.e. references to any kind of object,
including an array) are subject to "widening reference conversion" which
basically means you can pass an argument of a subtype where one of its
supertypes is expected.

I indeed needed arrays so I made two extra methods:
// This one returns a filled 2D-matrix with certain dimensions
public static Object[][] mathMatrix (int intColumns,
int intRows,
Object[] varElements) {
Object[][] M = new Object[intColumns][intRows];
for (int row = 0; row<intRows; row++){
for (int col = 0; col<intColumns; col++){
M[col][row] = varElements[intColumns * row + col];
} //col
} //row
return M;
}

// This one tries to add the contents of the two arrays
public static Object[][] mathPlus(Object[][] A,
Object[][] B) {
Object[][] ME;
for (int col = 0; col<A.length; col++) {
for (int row = 0; row<A[0].length; row++) {
ME[col][row]=A[col][row]+B[col][row];
} //row
} //col
return ME;
}

In another class I get a matrix with above method:
Object[][] M;
Object[] ints =new Object[] {11,12,53};
M=MathFunction.mathMatrix(1,3,ints);

....however when I test the method "mathPlus(Object[][] A, Object[][]
B)" with
N=MathFunction.mathPlus(M,M);
the error appears: "operator + cannot be applied to
java.lang.Object,java.lang.Object"

I suppose java doesn't know which primitives are contained in the
array, although I filled the array with ints. What am I missing here?

Nard
 
J

John C. Bollinger

Nard said:
John C. Bollinger said:
() Arguments of reference type (i.e. references to any kind of object,
including an array) are subject to "widening reference conversion" which
basically means you can pass an argument of a subtype where one of its
supertypes is expected.


I indeed needed arrays so I made two extra methods:
// This one returns a filled 2D-matrix with certain dimensions
public static Object[][] mathMatrix (int intColumns,
int intRows,
Object[] varElements) {
Object[][] M = new Object[intColumns][intRows];
for (int row = 0; row<intRows; row++){
for (int col = 0; col<intColumns; col++){
M[col][row] = varElements[intColumns * row + col];
} //col
} //row
return M;
}

// This one tries to add the contents of the two arrays
public static Object[][] mathPlus(Object[][] A,
Object[][] B) {
Object[][] ME;
for (int col = 0; col<A.length; col++) {
for (int row = 0; row<A[0].length; row++) {
ME[col][row]=A[col][row]+B[col][row];
} //row
} //col
return ME;
}

In another class I get a matrix with above method:
Object[][] M;
Object[] ints =new Object[] {11,12,53};
M=MathFunction.mathMatrix(1,3,ints);

...however when I test the method "mathPlus(Object[][] A, Object[][]
B)" with
N=MathFunction.mathPlus(M,M);
the error appears: "operator + cannot be applied to
java.lang.Object,java.lang.Object"

I suppose java doesn't know which primitives are contained in the
array, although I filled the array with ints. What am I missing here?

Evidently nothing. You described the cause of the problem quite
succinctly. To expand upon it a bit, however, you need to recognize a
few things:

(1) The methods need to be able to handle any argument compatible with
their formal parameter types. The specific arguments you pass to them
in some particular program don't factor into that analysis at all.

(2) You are _not_ loading the arrays with ints. Primitives cannot be
assigned to object references. Rather, you are making use of Java 1.5's
new "autoboxing" feature to load the arrays with objects of class
Integer. You cannot perform math on Integers, only on primitives.

(3) If you're having trouble seeing how to use a conversion trick to do
for arrays what you can do for primitives, it's because there is no such
trick. You do, however, have the option of declaring and using arrays
of Number objects. You cannot perform arithmetic directly on Numbers,
but you can get primitive values from them via their XXXValue() methods,
and perform arithmetic on those.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top