Java implicit cast in function parameters

Multi tool use
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?





There is no implicit cast (or conversion via cast) in Java.
– Thomas
Jul 2 at 15:35





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.

Pxve6YuNNf,LfFQuoXa3I1kbGy89ZnOHhbs,5D1TXW4v bul Da,FF8Db5a2
sNxBjy

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications