Java:分配了子类数组对象的超类数组对象 [英] Java : Super class array object assigned with sub class array object

查看:106
本文介绍了Java:分配了子类数组对象的超类数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为其子类分配一个子类对象数组.该程序编译成功,但是出现了 ArrayStoreException .我知道父级和子级数组是对同一数组的引用,但是我至少不能访问方法 func 吗?

I'm trying to assign a sub class object array to its super class. The program compiles successfully, but I' getting an ArrayStoreException. I know that arrays parent and child are references to same array, but shouldn't I be able to access method func at least?

class Pclass
{
    Pclass()
    {
        System.out.println("constructor : Parent class");
    }

    public void func()
    { 
        System.out.println("Parent class");
    }
}

class Cclass extends Pclass
{
    Cclass()
    { 
        System.out.println("Constructor : Child class");
    }

    public void func2()
    {  
        System.out.println("It worked");
    }

    public void func()
    { 
        System.out.println("Common");
    }
}

public class test
{     
    public static void main(String ab[])
    {    
        Cclass[] child = new Cclass[10];
        Pclass[] parent = child;
        parent[0]=new Pclass();
        parent[0].func();
    }
}

推荐答案

您不能这样做:

Cclass[] child = new Cclass[10];
Pclass[] parent = child;
parent[0]=new Pclass();

您应该尝试这样做:

Cclass[] child = new Cclass[10];
Pclass[] parent = child;
parent[0]=new Cclass();

这是因为,您首先将Pclass数组分配给只能具有Cclass对象的子引用,然后尝试将Pclass对象分配给父引用,这是不允许的!

That's because, You first assigned the Pclass array to the child reference that can only have Cclass objects, then you are trying to assign Pclass object to the parent reference, that's not allowed!

看,发生的事情是您在编写新的Cclass时在堆上创建了一个Cclass对象,尽管Cclass对象在数组中为null,但现在它们仅接受Cclass对象或其子类的对象

See, what happens is that you have created a Cclass object on the heap when you wrote new Cclass, though the Cclass objects were null in the array but now they would accept only Cclass objects or it's subclass's objects

所以分配Pclass对象将是非法的!

so assigning the Pclass object would be illegal!

获得运行时异常而不是编译时间的原因:

Reason for getting a runtime exception and not compile time:

编译器仅检查类是否在相同的继承层次结构中,因为它们在同一层次结构中,因此您会遇到运行时异常.

The compiler only checks whether the classes are in the same inheritance hierarchy or not, since they are in the same hierarchy you get a Runtime exception.

这篇关于Java:分配了子类数组对象的超类数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆