Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does upcasting works in Java?

I was going with the concept of upcasting and downcasting in java, which are also referred as widening and narrowing.

  • UpCasting (Widening) happens automatically from derived class to base class. i.e if it has a is-a relationship.
  • Downcasting has to be done explicitly for run time check.

Okay, I got the concept and everything. But, how its working in this case?

public class ObjPair {
    Object first;
    Object second;

    public ObjPair(Object first, Object second) {
        this.first = first;
        this.second = second;
    }

    public Object getFirst() {
        return first;
    }    
    public Object getSecond() {
        return second;
    }

    public static void main(String[] args) {
        ObjPair objPair = new ObjPair("A",2.2); // Goes widning conversion
        System.out.println(objPair.getFirst());
        System.out.println(objPair.getSecond());
    }
}

ObjPair objPair = new ObjPair("A",2.2);

  • This is going through upcast, String to object and Double to object and the state gets store in the objPair. Great..!!!

Now,when i do objPair.getFirst() and objPair.getSecond(). It returns me A and 2.2.

  • How does it remember the string and double, widening/upcast is supposed to remember the super-class states and methods.
  • How is it able to access sub-class types and values?
like image 582
Ritt Avatar asked Aug 18 '26 22:08

Ritt


1 Answers

Casting of object references does not change the object. It simply allows assigning it into a reference of a different type. The object itself remains the same.

In your case, it needs two Object references, it checks compatibility (no problem there), and then the references are set in variables of type Object. The instances themselves do not change. If they have methods that override those of Object, then the overriding methods will be called.

Thus, when it comes to the part where it prints the object, it simply uses String.valueOf, which calls the object's toString() method. The instance accessed from the Object variables is actually a String object, and String overrides toString() to return itself. Double also overrides toString. These overrides are called, as the instance is still an instance of String and an instance of Double. Only the reference is Object.

Note that you also have a cast from double to Double there. This implicit boxing does change the object - it takes a primitive and creates a new Double from it.

like image 137
RealSkeptic Avatar answered Aug 20 '26 13:08

RealSkeptic