Home > Net >  How Does Type Casting in Java Actually Work?
How Does Type Casting in Java Actually Work?

Time:02-18

Suppose A is a superclass of B and each have property i with default value is 0.

B b = new B();
System.out.print(b.i);
A a = b;
a.i = 3;
System.out.print(b.i);

Why the output is 00 not 03?

Does casting create new object?

Edit :

These are A and B :

class A {
    int i;
}
class B extends A {
    int i;
}

CodePudding user response:

Without seeing A or B it's somewhat hard to speculate, but it sounds like you have a second field i in B that shadows the field i in A. Here is a complete self contained example,

static class A {
    public int i = 0;
}

static class B extends A {
    public B() {
        this.i = 2;
    }
}

public static void main(String[] args) {
    B b = new B();
    System.out.println(b.i);
    A a = b;
    a.i = 3;
    System.out.println(b.i);
}

And that outputs

2
3

Clearly demonstrating that casting does not create a new object.

  • Related