Search code examples
javanesteddowncast

Is this the correct way to implement upcasting and downcasting in the following java code?


package test;
public class Test {

     public static void main(String[] args) {
        A a2 = new B();               // 1
        a2.display1(); 
        a2.display();
        ((B) a2).display2();          //  2
        ((A) a2).display();           //  3
        B b1 = new B();
        b1.display1();                //  4
     }
}

class A {
    int a = 10;

    void display() {
        System.out.println("parent class " + a);
    }

    void display1() {
        System.out.println("parent class " + (a + 10));
    }
}

class B extends A {
    int a = 30;

    @Override
    void display() {  
        System.out.println("child class " + a);
    }

    void display2() {
        System.out.println("child class " + (a + 10));
    }
}
  1. whose object is created ?class A or B.
  2. Is this downcasting
  3. why this is not invoking the method of class A? how to invoke method of class A (override one) with this object and not with the object of A.
  4. is this implicit upcasting?
  5. If a class A have a nested Class B than during object creation of class A does object of class b is also formed ?i was not able to use method of class B from object of A

Solution

    1. You do new B(), so obviously a B object is created.

    2. Yes, from the type A to the subtype B which is down the class hierarchy.

    3. Because a2 refers to a B object and which method is called is determined dynamically (at runtime, instead of at compile time) by looking at what the type of the actual object is.

    4. No, there's no casting going on here at all.

    5. I don't understand exactly what you mean here. The type of the variable determines which methods you can call, but which method is actually called depends on the actual type of the object that the variable refers to.