Java implicit cast in function parameters

Multi tool use
Java implicit cast in function parameters
Is it possible to automatically cast an integer to an object when passing it as function parameter? i have this function prototype:
public void aggiungiA(Nodo x)
Nodo has his own constructor with an integer parameter. Now, What i want do is:
aggiungiA(5);
with an implicit cast.
is there anyway to do it?
No you cant do this directly. Consider to use somethink like factory pattern.
– Emre
Jul 2 at 15:39
2 Answers
2
There are no implicit casts via constructor invocations in java. You'll have to explicitly call the constructor - either from the caller, or by overloading the method:
public class MyClass {
public void aggiungiA(int i) {
aggiungiA(new Nodo(i));
}
public void aggiungiA(Nodo x) {
// Do something with X
}
}
In addition to @Mureinik's answer, I guess you are coming from a C++ background where certain casts do happen automatically. In Java things are different - the only implisit casts are:
long x = myLong + inInt
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
There is no implicit cast (or conversion via cast) in Java.
– Thomas
Jul 2 at 15:35