2

If I were to use something like:

Class object = (Class) object;

would that reinstate the object with the current properties or would it be the same object under another class? I want to make sure I'm not reinstating the same thing over and over because I'm going to use code like this in a render method.

Peppy8651
  • 23
  • 2
  • 5
    There is no such term as 'reinstate' in the Java world. Do you mean re-instantiate? Instantiation is a thing (`new` keyword), but re-instantiation is not. Anyway, it's called a **cast**. Nothing is created. It's just a directive to the compiler saying "*I know better than you what the type of this is, so force it to assume that type*" – Michael Apr 13 '21 at 19:41
  • There is a class `Class` in Java. In your example, it is somewhat hard to figure if you mean casting to any class or specifically to `Class` class. If you meant casting to some class, in the future consider doing something like `SomeClass object = (SomeClass) object;` for clarity. – hfontanez Apr 13 '21 at 20:13

2 Answers2

2

It would be helpful if you provided more of a context as to what you are trying to achieve. I think what you have written now would throw a "Variable 'object' is already defined in the scope" error.

If you are trying to cast object to type Class, you would need to use a different variable name such as:

Class object2 = (Class) object;

This does not create or re-instantiate anything, the variable object2 still points to the same object.

For a more extensive answer on how casting is handled:

How does Java Object casting work behind the scene?

  • 1
    "If you are trying to cast object to type Class" - I don't think you "cast" any object to `Class`. Just simply do `Class clazz = object.getClass();` Then, use `>` if the object class is not known, or the name of the class if known. For example ``. – hfontanez Apr 13 '21 at 20:18
  • Thank you, and yes, I should've been more specific with my object names. Your example code is what I meant with the question. – Peppy8651 Apr 14 '21 at 14:51
0

No new instance is created in your example. You're just casting it's type into a different type.

cwittah
  • 349
  • 1
  • 3
  • 17