Search code examples
javatypecasting-operator

Unable to perform typecasting -incompatible type, int cannot be converted to c2


This is a simple code that I have written:

class c1
{
    int x = 10;
}
class c2 extends c1
{
    int x = 20;
}
class c3
{
    public static void main(String [] args)
    {
        c1 a = new c2(); 
        System.out.println(a.x); //This works and output is 10.
        System.out.println((c2)a.x); //Error is here
    }
}

And the error says,

incompatible type, int cannot be converted to c2

I am sure the code is correct. Since the type of reference a is converted to c2 (in the statement where error is being displayed), 20 should be displayed.

But, typecasting is not happening. Why?


Solution

  • Should be ((c2) a).x

    You need to have an extra parenthesis to make sense. Because the compiler thinking that you are trying to case whole thing to c2.

    System.out.println(((c2) a).x);