Casting to superclasses and interfaces
Details:
This code show the basic principle that labels constrain the object they are attached to, but don't change its underlying form. This allows COM-style interface frameworks to work smoothly.
Original author/s: Andy Evans
Original location/s:
License: none
Imports and instance variables:
N/A
Code:
class Casting {
public Casting () {
AClass aObject = new AClass();
// Objects constrained by one interface can be cast into another interface
// the underlying object implements.
Interface1 interface1 = (Interface1) aObject;
Interface2 interface2 = (Interface2) interface1;
// Objects cast into one class type it extends can be cast into another class
// further up the extension heirarchy and back again.
BClass bObject = (BClass) aObject;
CClass cObject = (CClass) bObject;
AClass aObjectAgain = (AClass) cObject;
}
public static void main (String args[]) {
new Casting();
}
}
interface Interface1 {
}
interface Interface2 {
}
class AClass extends BClass implements Interface1, Interface2 {
}
class BClass extends CClass {
}
class CClass {
}