The Artima Developer Community
Sponsored Link

Java Answers Forum
java mechanics

2 replies on 1 page. Most recent reply: Feb 9, 2005 4:58 AM by Sandu Crasteti

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Sandu Crasteti

Posts: 13
Nickname: xan
Registered: Feb, 2003

java mechanics Posted: Feb 9, 2005 1:49 AM
Reply to this message Reply
Advertisement
Hello!

Please help me grasp some concepts that might have something to do with (at least) the inheritance mechanisms.
Consider the following situation: after creating a class A (with 3 instance variables and 5 methods, including the constructor), another class, B, is created, extending A. This new class has one additional instance variable, two additional methods, and a method overriding one of the A’s methods.
When an A[] array is declared, it appears that it can hold objects of type B, but a B[] array cannot hold objects of type A.
Also, both type of objects can be stored in an Object[] array, given that both A and B extend (by default, as far as I know) the Object class (with its 11 own distinct methods) – but none of A[] or B[] can store Object objects.
What I cannot understand so far is why a “smaller” (at least apparently) location can hold a “bigger relative” object, while the opposite is not possible.
I am sure that I’m missing (or confusing) something – but what is that?


Best regards,

Sandu Crasteti


Sudhakar

Posts: 2
Nickname: sudhu
Registered: Feb, 2005

Re: java mechanics Posted: Feb 9, 2005 4:39 AM
Reply to this message Reply
when you declare an array A[] the type is of class A. B extends A. Casting
type B to Type A is admissible since all the methods of A are existing in B
and calling any method of A on B would be allowed. But if you put A in B[]
then they type is of class B, which has more methods than A.If using B's
type you access a method which doesn't exist in A, that wouldn't be
allowed. Hence the restriction of putting objects of class A in array of
B[].
Same argument is applicable to 'Object' objects being put in either A[] or
B[].

Sandu Crasteti

Posts: 13
Nickname: xan
Registered: Feb, 2003

Re: java mechanics Posted: Feb 9, 2005 4:58 AM
Reply to this message Reply
Thank you!

Flat View: This topic has 2 replies on 1 page
Topic: can't run an applet Previous Topic   Next Topic Topic: Creating JCreator Syntax

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use