if I want to make a method that does something to any object that is used as input, I can write a method header that looks like this:
public static void example(Object o){...}
is there a term for "all primitive types" the same way that Object
contains all non primitive variables?
CodePudding user response:
You can use Wrapper type for primitives. Then, they become objects and you can use them wherever you can use Object.
public class Main{
static void print(Object o){
System.out.println(o);
}
public static void main(String[] args) {
Integer i = 5;
Double d = 5.5;
Boolean b = true;
print(i);
print(d);
print(b);
}
}
CodePudding user response:
I'm not sure if there is a type that encompasses only primitive types, but you can use a wrapper type and throw an error if the input given is not of one of those types.
public static void example(Object o) {
if(!(o instanceof Double)) {
throw new RuntimeException("Error Message");
}
}
This code only checks the Double
wrapper type, but you get the idea.
CodePudding user response:
No, but method overloads are usually how that is accomplished. For example:
// Notice this method is private.
private static void exampleImpl(Object obj) { /* ... */ }
// And these are public, so it is only possible for an outside caller
// to pass (wrapped) primitives to the above method.
public static void example(boolean value) {
exampleImpl(value);
}
public static void example(byte value) {
exampleImpl(value);
}
public static void example(char value) {
exampleImpl(value);
}
public static void example(short value) {
exampleImpl(value);
}
public static void example(int value) {
exampleImpl(value);
}
public static void example(long value) {
exampleImpl(value);
}
public static void example(float value) {
exampleImpl(value);
}
public static void example(double value) {
exampleImpl(value);
}
CodePudding user response:
There is not such thing, but you can use wrapper types with generics. Here is a simple program to demonstrate this:
public class Test{
static <T> void genericMethod(T t){
System.out.println(t);
}
public static void main(String[] args) {
Integer intNum = 10;
Double doubleNum = 36.5;
Boolean aBoolean = true;
Character character = 'a';
genericMethod(intNum);
genericMethod(doubleNum);
genericMethod(aBoolean);
genericMethod(character);
}
}