In dynamic languages like Python/Smalltalk/Scheme, you usually don't need
cast. Because "the methods a particular instance can perform" becomes the
type of the instance, it's not as important which class that instance
actually belongs. At instantiation time, "all the methods the instance can
perform" is determined. At runtime, you either can call the method or you
get an AttributeError.
>>> import java
>>> v = java.util.Vector()
>>> v.add(java.util.Properties()) # Properties extends Hashtable
>>> p = v.elementAt(0)
>>> h = v.elementAt(1)
Traceback (innermost last):
File "<console>", line 1, in ?
>>> p.getProperty("abc") # works ok, just returns None
In the above example, the JVM+jython knows you can can call contains() on
both p and h, but you can only call getProperty() on p.
You can see that you don't need casting when assigning the returned Object
from v.elementAt() to a variable. Java must keep some class information
available at runtime for polymorphism to work, otherwise even with cast you
wouldn't know whether you can perform a certain method call or not.
BTW, this topic probably should be in jython-users list instead..
----- Original Message -----
From: "Stuart Swerdloff" <stuarts@...>
Sent: Friday, June 29, 2001 2:31 PM
Subject: Re: [Jython-dev] casting
> It isn't clear to me how object 'y' would be of Class myJavaClass2...
> Without any additional information, I would expect Jython to assign y to
> a reference to x, of Class myJavaClass1. Unless y had been previously
> or referenced to (assigned to?) an object of Class myJavaClass2.
> I have had some difficulty in dealing with this (upcasting) in Java, and
> resorted to
> a shallow copy based on reflection...
> Kevin Butler wrote:
> > marco wrote:
> > >
> > > hy there,
> > >
> > > how can i cast a java-instance to another type.
> > > ex.
> > > x = myJavaClass1()
> > > y = (myJavaClass2) x
> > In Jython, that looks like:
> > x = myJavaClass1()
> > y = x
> > :-)
> > No casts needed.
> > kb
> > _______________________________________________
> > Jython-dev mailing list
> > Jython-dev@...
> > http://lists.sourceforge.net/lists/listinfo/jython-dev
> Jython-dev mailing list