Answer the question
In order to leave comments, you need to log in
Why does the class store 3 objects?
example from Bruce Eckel's "Java Philosophy" (page 503):
class Automobile {}
public class Holder2 {
private Object а;
public Holder2(0bject а) { this.a = а; }
public void set(Object а) { this.a = а; }
public Object get() { return а; }
public static void main(String[] args) {
Holder2 h2 = new Holder2(new Automobile());
Automobile а = (Automobile)h2.get();
h2.set("Not an Automobile");
String s = (String)h2.get();
h2.set(1); // Автоматическая упаковка в Integer
Integer x = (lnteger)h2.get();
}
Now you can store anything in Holder2 - in the above example, one
Holder2 class stores objects of three different types.
Holder2 h2 = new Holder2(new Automobile());
h2.set("Not an Automobile");
h2.set(1);
Holder2 h2
Answer the question
In order to leave comments, you need to log in
The point is that Holder2 can store and return an object of any type, due to the fact that all objects are inheritors of the Object class.
Stores a string in the holder - an object of type String
Stores in holder 1 - which is stored there as an Integer
And yes, you understand everything correctly, we lose the previous values.
Phrase
h2.set("Not an Automobile")
h2.set(1)
stores objects of three different typesyou need to understand how it "saves" (in the above example, objects of three different types were stored in one Holder2 class), but only one was stored at a time.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question