Search code examples
javaobjectvariablesreferenceassign

How does Java variables work when assigning one object type to another object type?


I'm no really sure how to explain my doubt right away, so I'll start with an example. I have the next lines:

Object myObject = null;
Integer myInteger = 10;

myObject = myInteger;

Basically, I know I can assign one subclass object to a superclass object (in this scenario, myInteger of type Integer to myObject of type Object). So far so good, but now... let's say I want to get the class of myObject.

System.out.println("myObject: " + myObject.getClass());

And it prints this:

myObject: class java.lang.Integer 

It says is of type Integer!

I know a variable actually stores a reference to the actual object in memory, so the method getClass() is returning the class of the actual object. But then...

  1. Why can't I access the methods of the class Integer through myObject since is pointing to an object of type Integer? I mean, why can't I do something like this? myObject.intValue();

  2. If I can only access to the methods of Object through myObject (even though it's pointing to an object of type Integer), how does Java know which methods can be called through myObject? the variable itself stores a type of class?

Basically, I would like to know what information Java stores in the variables, is it only a reference? or it also has a class name? how the variable know which methods can be called if it has assigned a reference to a subclass object?

I hope my doubt is clear, and excuse my grammar.


Solution

  • Consider this analogy: you provide storage services with three tiers of "safety level": General goods, Valued items, and Luxury items. You have an online system that lets your clients book space and make payments based on what they want to store. Depending on the tier, your services and booking requirements are different:

    General goods:

    • You get space in shared warehouse
    • You pay by item volume

    Valued items:

    • You get storage space in shared warehouse
    • You get additional security with camera surveillance
    • You pay by item volume

    Luxury items:

    • You get dedicated storage space with a location label
    • You get camera surveillance and security guards watching your items 24/7.
    • You pay by item value.

    Now, consider that your clients bring items in boxes marked with a reference number issued by your reservation system and your security guards on location inspect the content.


    Let's see what your process steps do:

    Online system:

    • Lets your clients declare what tier they're going to buy
    • Reserves storage room for the declared booking
    • Based on client's booking, charges their payment method with the correct amount
    • Offers a tracking system that shows basic details of physical storage

    Security guards:

    • Inspect the actual physical items clients present in a box
    • Ensure items are as per booking, but gold can be stored in general goods area if the client chooses to do so, but old plastic cups can't be taken to luxury items for insurance's sake.

    What do you think of these scenarios?

    • A client uses your online system to book general goods storage and completes the booking. When they come back to check the status of their items: will the system let them see the name of the security guard watching their item 24/7?
      Hint: no, the system knows that they have general goods tier and that offers no dedicated guarding services.
    • The same client puts gold in the box and presents it at the location.
      • Will the online system let them see details of 24/7 guarding or the video footage?
        Hint: no (still), because the system knows that it's a general goods reservation.
      • Will the guard who checked them in know that it's gold in the box rather than cheap items?
        Hint: yes. But still, the client will not get luxury items service. Right?
    • A different client makes a "luxury items" booking, but presents a box with an old plastic cup inside.
      • Will your online system prevent them from doing this?
        Hint: no, it can't, because it doesn't know what's in the client's mind and it can't inspect the item.
      • Will your guard on-site be able to prevent this box from being checked in?
        Hint: yes, because they can see the physical item and determine what it actually is. And because insurance forbids low-value items in higher tiers, the guard can stop this.

    So it is with Java (roughly speaking):

    • Declaring a variable and giving it a type => making a booking and declaring the kind of good
    • Assigning a value to a declared variable => putting an item in a box and presenting it to the guard for inspection
    • Calling a method on a declared variable => using services or tracking online (you can't get services your tier doesn't entitle you to: even if you have gold in general goods, you can't get video footage)

    In other words, the online system is like the compiler, and the physical location is like the runtime.
    In Java, the type of tier you reserved online is known as "static type", it's the type known at compile-time (at booking time). The actual type you put in the box is known as the "runtime class", being dynamic (just as a general goods tier box can be allowed to take in gold, or a mid, valued item like a TV).

    Just as with the box, only the runtime knows the actual/runtime class of the variable: only the staff on-site will know that it's gold in the box. And when you call myObject.getClass(), that's exactly what you're asking for: the runtime class of myObject (this is the class whose constructor is called or with which new is used; or in some cases, the class of the literal, such as 10 for int or Integer, but this is a story for another day). But even if at runtime it's known to be an Integer, the compiler (online system, remember?) won't let you call methods that are on Integer because myObject was declared as Object: the online system won't let you see video footage of a general goods booking even if the box holds diamond. You can force the compiler to accept Integer's methods on myObject with a type cast, as shown in Sweeper's good answer, and this is a little like upgrading to luxury items on site, after which the online system will let you get higher tier services :)


    This analogy is possibly ridiculous in some aspects, such as in the fact that the compiler prevents you from assigning an incompatible or broader-typed value to a variable... but it's just an example, a limited one.