I am having trouble understanding a part of class slide that says:
Storing Items in an ArrayBag :
We store the items in an array of type Object.
public class ArrayBag implements Bag {
private Object[] items;
private int numItems;
....
}
This allows us to store any type of object in the items array, thanks to the power of polymorphism:
ArrayBag bag = new ArrayBag();
bag.add("hello");
bag.add(new Double(3.1416));
Is ArrayBag a specific type of object or is it just a Obj variable name?
Why do we need to cast 3.1416 as a Double and add a new?
(I know the code could be just be bag.add(3.1416) and Java will autobox it for you, but I'm having trouble understanding the meaning behind bag.add(new Double(3.1416)).
Is ArrayBag a specific type of object or is it just a Obj variable name?
ArrayBag
is neither the specific type of object not its a Obj variable, its actually a Class.
Why do we need to cast 3.1416 as a Double and add a new?
No you need not to explicitly cast the double
as AutoBoxing
comes into picture (Java 1.5 and above) and convert double
to Double
ie from primitive to Object.
I'm having trouble understanding the meaning behind bag.add(new Double(3.1416)
bag
is actually an instance of ArrayBag
, and add()
is a method defined in this class, which takes a parameter of type Object
and might be adding it in items
array, which is nothing but an array of Object
.