ArrayStoreException in inheritance

I work with inheritance when I encounter such a problem. my code is as follows

   public class Parent {
        public void methodParent() {
            System.out.println("Parent");
        }
   }
   public class Child extends Parent {
    public void methodParent() {
        System.out.println("override method in Child");
    }

    public void methodChild() {
        System.out.println("method in Child");
    }
   }
   public class MainTest {
    public static void main(String[] args) {
        Child[] c = new Child[10];
        Parent[] p = c;

        p[0] =  new Parent();
        c[0].methodParent();
    }
  }

stack trace

Exception in thread "main" java.lang.ArrayStoreException: com.test.Parent
    at com.test.MainTest.main(MainTest.java:10)

when i debug check c then i got a message like

org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.

please help me understand what the problem is.

+4
source share
4 answers

When you do it

    Child[] c = new Child[10];
    Parent[] p = c;

you tell the compiler that pthis is just an array of the parent. However, there is also a runtime check that the array should still contain references Child. This is a runtime check.

+2
source

See ArrayStoreException:

, , . , ArrayStoreException:

 Object x[] = new String[3];
 x[0] = new Integer(0);

, . . :

p[0] =  new Parent();

p Parent, Child , .

, , , Parent is Object Child is Integer.

+2

, . , ArrayStoreException:

 Object x[] = new String[3];
 x[0] = new Integer(0);

, Parent[] p = c;

:)

+1

, 'p', Child []. "" . , " ".

[] Parent [] , ( ). jvm, .

+1

All Articles