🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.java.help
Article #154

Re: Help -- Java Error

#154
From: Patricia Shanahan
Date: Sun, 08 Aug 1999 00:00
71 lines
2462 bytes
Note that "{" got lost somewhere, I'm assuming they are where they
need to be.

The key problem is that you created an object of class array of B with
space for 5 elements. That means you can put references to B in it, or
references to objects of any class derived, directly or indirectly,
from B. You cannot put an A reference in it, because A is a superclass
of B, not a subclass.

A is a superclass of B, so any array of B references can only contain
references that could also be in an array of A references. It is O.K.
to use a variable of type A[] to refer to an object of class B[], but
like any object its class does not change.

If you want the array to contain a mixture of references to A and to
B, instantiate it as a A[5], not B[5].

Patricia


Shashank wrote:
> 
> Consider the following Java Program
> 
> class A
> 
>     int id;
>     A()
> 
>        id = 1;
>     }
>     A(int i)
> 
>        id = i;
>     }
>     public int id()
> 
>        return id;
>     }
> }
> class B extends A
> 
>     B(int i)
> 
>     }
> }
> public class FinalC
> 
>     public static void main(String[] args)
> 
>        A[] array = new B[5];
>        array[0] = new B(10);
>        array[1] = new B(8);
>        array[2] = new B(6);
>        array[3] = new A(4); // line 23
>        array[4] = new A(2); // line 24
>        for(int i = 0; i< 5; i++)
> 
>           System.out.println(array[i].id());
>        }
>     }
> }
> 
> The execution returns the exception:
> 
> java.lang.ArrayStoreException:
>         at FinalC.main(FinalC.java:23)
> 
> Why the program runs in this way.
> What Changes should I make to the instructions on lines 23 and 24 to correct
> the problem.
Technical Details
Message-ID: <37AE5DF1.D63E05CE@acm.org>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail
References: <7olh27$sb$1@news.chorus.net>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 10568c,fe1ae2c02024cf32
X-Google-Attributes: gid10568c,public
X-Google-Thread: fb99b,fe1ae2c02024cf32
X-Google-Attributes: gidfb99b,public
X-Google-Thread: 113ae9,fe1ae2c02024cf32
X-Google-Attributes: gid113ae9,public
From: Patricia Shanahan <pats@acm.org>
Subject: Re: Help -- Java Error
Date: 1999/08/08
Message-ID: <37AE5DF1.D63E05CE@acm.org>
X-Deja-AN: 510527571
Content-Transfer-Encoding: 7bit
References: <7olh27$sb$1@news.chorus.net>
X-Accept-Language: en-GB,en-US,en,fr
Content-Type: text/plain; charset=us-ascii
Organization: Who? Me? Organized?
Mime-Version: 1.0
Newsgroups: comp.lang.java.help,cz.comp.lang.java,de.comp.lang.java