-3

I want to access the variable 's' using the array of objects 'arr'? Please refer the code snippet.

    public class Array_Chp3 {
        public static void main(String[] args) {
        Array_Chp3[] arr = new Array_Chp3[3];
        arr[0] = new str();  // when used this line instead of the below line , getting the error "s cannot be resolved or is not a field"
        //arr[0] = new Array_Chp3(); // when used this line instead of the above line, getting the error s cannot be resolved or is not a field
        str obj = new str(); 
        System.out.println(arr[0]);
        System.out.println(arr.length);
        System.out.println(arr[0].s); // How to access the variable 's'?

        }
    }
    class str extends Array_Chp3{
         public String s = "string123 @ str"; 
    }

Error Message: Exception in thread "main" java.lang.Error: Unresolved compilation problem: s cannot be resolved or is not a field at Array_Chp3.main(Array_Chp3.java:17)

2 Answers2

1

Your array is an array of Array_Chp3. That means that you decided that elements of this array are instances of Array_Chp3. You don't really care what concrete type they have, as long as they are instances of Array_Chp3.

What you store in its first element is a str instance. That's fine, since a str is a Array_Chp3 (it extends Array_Chp3).

But since the type of the array is Array_Chp3[], the compiler can't guarentee that its element are all instances of str. All it can guarantee is that they're instances of Array_Chp3.

You know that it's a str though, so you can tell the compiler: trust me, I know it's in fact a str. That is called a cast:

System.out.println(((str) arr[0]).s);

But it shows a design problem. If you need the elements to be instances of str, then the array should be declared as an array of str.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

If you know it is str you can cast it like this:

System.out.println(((str)arr[0]).s);
bohuss
  • 336
  • 2
  • 8