Question

I'm sorry if this is already asked but here is my question. I would like to create a function where the parameter that the user inputs can be any variable type, similar to System.out.println().

That being said how would I create that method?

public static void example(String, int, double, etc.) {
    //Code here
}
Was it helpful?

Solution

You need to change all the method parameters types to Object.

public void myMethod(Object o){
    // ...
}

Please note that in order to access o as a certain type of other class you will need to first test if it is in fact that class with if(o instanceof OtherClass) and then cast it with OtherClass o2=(OtherClass) o. Casting is expensive (hogs a lot of CPU (for a simple operation)) though so avoid if possible. If you just need a string representation of o then just call o.toString().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top