I
I
iscateli2021-12-26 18:59:32
Java
iscateli, 2021-12-26 18:59:32

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.


What are the three objects? I see only one created object: I suspect that they implicitly create objects, but then even if this is the case, then the reference variable is the same, if it starts pointing to another object, then nothing points to the old one and it is lost. I'm completely confused, please help me figure it out.
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

1 answer(s)
S
Sergey Vodakov, 2021-12-26
@iscateli

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 types
you 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.
Because of such translation errors, it is recommended to read books on programming in the original language.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question