Sorry for noobish question, but why we even use String
, int
and others, if we can just use Object as a type?
I mean use Object one;
instead of String one;
Sorry for noobish question, but why we even use String
, int
and others, if we can just use Object as a type?
I mean use Object one;
instead of String one;
For example, the String
class declares a bunch of methods. If your variable is declared as Object
, then only the methods declared in Object
and its super classes (none) are visible on that variable, regardless of the type of the actual object.
You can do
String one = new String("whatever");
System.out.println(one.length());
but you can't do
Object one = new String("whatever");
System.out.println(one.length());
Methods and fields are resolved on the compile time type of the variable.
Because in some cases if you know, you will have a String
, it's better to use:
String str = "foo";
int length = str.length();
instead of doing it with typecasting like this:
Object str = "foo";
try {
int length = ((String)str).length();
} catch (ClassCastException e) {
// and now what?
}
by not knowing if str
is really a String
!
The class Object
is only providing the Object
s methods. So you can't access for example this length()
method on an Object
.
So, everytime you know, that you will only able to handle a String
, use a String
!
If you are not sure what you will have, you have to use Object
and do your special logic around (typecasting, error handling on a ClassCastException
and so on...).
Because Object
is the lowest common denominator. It's also not type safe and you would have to cast to the specific type each time you wanted to do something specific to that class.
Quite a few reasons really..
Try and use charAt
on a String
object, referred to by an Object
type reference. If we only used Object
type references, we would only be able to use Object
methods, which aren't exactly useful.
Some methods require String
types, and not Object
types. For example, string.substring()
takes one or two arguments
of type int
. This will not compile if you pass an Object
in, unless you cast it. Which means, every time you want to use some native Java functionality that doesn't accept type Object
, and requires a more specific reference type, you've got to cast it... which is most of the time.
So the code makes some bloody sense. Using these types means that you automatically know the kind of data that it will hold, just by looking at the variable type. String
will hold some text. int
holds an integer, double
holds a large decimal. This all helps in making code more readable, and thus more extendable.