public class helloworld {
public static void main(String[] args) {
String text = "Hello World";
l(text);
int n = 0;
l("--------------------------");
l(n);
}
public static void l(Object obj) {
System.out.println(obj);
}
}
I wrote this simple program in Java and it worked. Now I am confused that if all the data types (int
, char
, double
etc.) come under Object
, then why do we specify which data type we want to accept when we pass values?
I mean we can always use the data type Object
as used in the function l
. Is there a specific reason why people don't always use Object
as their data type to pass values?
There is an implicit conversion defined between all primitive types and their respective object counterparts:
int -> Integer
char -> Character
etc...
This is called autoboxing.
Is there a specific reason why people don't always use "Object" as their data type to pass values?
Since Java is strongly typed, you cannot do a whole lot with Object
.
E.g. try this:
static Object add(Object a, Object b) {
return a + b; // won't compile
}
This is because methods, operators, etc. available to use depend on the static type of the variable.
println
can accept Object
because it only needs to call the toString
method. If you only need the limited functionality provided by the methods in Object
, then sure, you can use it as a type. This is rarely the case, however.
For the primitives you mentioned, they are not really objects, they will simply be boxed to their representation as an object. An int
would become an Integer
, a long
would become a Long
etc.
Read this article about Autoboxing in java.
As for your question
Is there a specific reason why people don't always use "Object" as their data type to pass values?
If you specify Object
as the parameter of your method you won't be able to call the methods the real object contains without doing a cast. For example, if you have a custom object AnyObject
that contains a method anyMethod
, you won't be able to call it without casting the object to AnyObject
.
It will also be unsafe as you will be able to pass any type of object to a method which may not be designed to function properly with any of these types. A method containing only System.out.println
is not representative of a real use case, it will work with any object simply because by default the println
will call the toString
method which is already defined in an Object
.
While it does look like a function that appears to accept all types of parameters, you will have to deal with these
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With