1

The Program is:

class A
{
   int i = 10;
}
class B extends A
{
   int j = 20;
}
class C extends B
{
   int k = 30;
}
class D extends C
{
   int m = 40;
}

public class asg2
{
   public static void main(String[] args)
   {
       A[] a = {new A(),new B(), new C(), new D()};

    System.out.println(a[3].i); //No error!!!
    System.out.println(a[2].j); //throws error 
    System.out.println(a[1].k); //throws error (Understood why error)
    System.out.println(a[0].m); //throws error (Understood why error)
}

}

I understand why the last two throw error. But I dont understand why the 2nd print statement throws error. And first one runs smoothly.

asg2.java:29: error: cannot find symbol         
System.out.println(a[2].j);                                    
                       ^
symbol:   variable j                    
location: class A                                              

2 Answers 2

5

The compiler does not see the element a[2] of type C. It sees it of type A because that's the type of the declared array. Hence it cannot accept accessing a field that belongs to a subclass of A. If you cast the element to C, the compile will accept it:

System.out.println(((C) a[2]).j); // compiles OK
Sign up to request clarification or add additional context in comments.

Comments

2

Every entry in your array a is of type A. It might actually be holding an instance of B or C or D, but the variable is of type A, because that is how your array was declared. So you can't access fields that A doesn't have (unless you cast to another type, telling the compiler explicitly what type you think the object is).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.