On Wed, 3 Nov 1999 15:11:16 +0530 (IST), SABYASACHI S GUPTA wrote:

>
>I have 3 files to test this.
>
>//A.java
>public class A {
>       public void method(){
>               System.out.println("In A");
>       }
>}
>
>
>//B.java
>public class B extends A {
>
>       public void method()
>       {
>               System.out.println("hello world");
>       }
>}
>
>//mymain.java
>
>import A;
>import B;
>
>public class mymain{
>
>        public static void main(String args[])
>        {
>                B b=new B();
>                A a=new A();
>
>                b = (B)a;
>
>                b.method();
>        }
>}
>
>Since this requires an explicit cast I did just that
>But I get a runtime error
>
>Exception in thread "main" java.lang.ClassCastException: A
>        at mymain.main(Compiled Code)

This is a generic Java question...

The answer is that "a" is not a "B" object.  You can not cast
something to something it is not.

B is a subclass of A which means that "b" (which is of class B)
can also be considered to be of class A but "a" (which is of class A)
can not be considered of class B.

This is SOP in object oriented languages.  In C++ the compiler may
be able to catch this at compile time or RTTI will catch it at run
time.  In Java it is usually just caught at run time since it checks
the actual reference.

For example, if you coded:

                B b;
                A a=new B();

                b=(B) a;

This would work since the object stored in a is actually more
than just of class A it is of class B (which is a subclass of A
and thus also of class A thus the first assignment is valid)

In this case the a references an object that can be "cast" to a
object reference of class B and thus at run time it will work.

If you later do:

                a=new A();
                b=(B) a;

This would fail since a now contains an object that can not be
looked at as an object reference to a class B object.

-- 
Michael Sinz ---- Technology and Engineering Director/Consultant
"Starting Startups"                 mailto:[EMAIL PROTECTED]
My place on the web ---> http://www.users.fast.net/~michael_sinz



----------------------------------------------------------------------
To UNSUBSCRIBE, email to [EMAIL PROTECTED]
with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]

Reply via email to