0
class X {              //Super class
    int a=10;
    public void data() {
        int b=10;
        System.out.println(b);
    }
}

class Y extends X {    //Subclass
    int a=20;
    public void data() {
        int b=20;
        System.out.println(b);
    }
}



public class Casting {
    public static void main(String[] args) {
        X x = new Y();
        System.out.println(x.a);   //Prints a=10 : Value of superclass
        x.data();                  //Prints b=20 : Value of subclass
    }
}

I know that this has something to do with Upcasting and Downcasting. But in that case shouldn't both the values be of the same class.

Edit: Fixed it! Turns out, when

X x = new Y();

is executed, x holds the original value of its fields(variables) but retains the value of any method that is overridden in the subclass.

Therefore, the instance x holds:

a=10

public void data() {

int b=20;

System.put.println(b);

}

96var3
  • 567
  • 4
  • 11

0 Answers0