Reputation: 2014
Object a[] = new Object[2];
a[0] = "asd";
a[1] = 1;
I am seeking an explanation to how this is possible in Java. I did look at the implementation of Object and I must ask for some help to understand it.
Creating a variable that can hold any type in e.g. Python is built-in but in Java we need the Object class.
What is it in the implementation of Object that allows it to have any type, and please whats the explanation?
Upvotes: 3
Views: 488
Reputation: 16498
Imagine, you have a class animal
class Animal {
...
}
and further classes which extend the animal class, for example a class dog and another class cat:
class Dog extends Animal {
...
}
class Cat extends Animal {
...
}
In a container (array, list ...) you now want to store different objects. The following things are probably obvious:
Dog[] dogs = new Dog[2];
dogs[0] = new Dog("Bobby");
dogs[1] = new Dog("Jack");
Cat[] cats = new Cat[2];
cats[0] = new Cat("Cathy");
cats[1] = new Cat("Jenny");
What is not possible is to store a dog in a cat array or vice versa. So the following does not work:
cats[1] = new Dog("Tommy"); or dogs[1] = new Cat("Tammy");
But if you want to have different animals in an array, this must be of type a superclass of all the animals that are to be stored in it
Animal[] pets = new Animal[3];
pets[0] = new Dog("Bobby");
pets[1] = new Cat("Cathy");
pets[2] = new Fish("Nemo");
As already mentioned in the comments and the above answer, Object is the supper class of all classes in java. Even if you write your own class, it extends the object class.
The following things are equivalent:
class MyOwnClass { ... }
class MyOwnClass extends Object { ... }
This means even if it does not explicitly state so, each class extends the object class. So if object is the superclass of all other classes, you can do in an array of type object the same as you did with your animal array. That is, store different animal types in it. Therfore (since all classes inherit from the object), the following applies, even if it does not make much sense
Object[] objects = new Object[6];
objects [0] = "Some String";
objects [1] = 42;
objects [2] = Double.NEGATIVE_INFINITY;;
objects [3] = new Dog("Bobby");
objects [4] = new Cat("Cathy");
objects [5] = new File("C:\\temp\\test.txt");
Upvotes: 0
Reputation: 140457
Let's go step by step:
Object
is the root of all reference types in Java. Anything that is a reference, is also instanceof Object
!a[0] = "asd";
assigns a String. Strings are Objects by default.a[1] = 1;
leads to auto-boxing. You are assigning an Integer object to that array slot, not a primitive int value of 1.And of course, covariance is also worth mentioning here.
Upvotes: 7