Use a reference variable to refer to any object that is a subclass of the declared reference variable type : Reference Type Casting « Type Casting « SCJP
class Foo {
publicvoid doFooStuff() { }
}
class Bar extends Foo {
publicvoid doBarStuff() { }
}
class MainClass {
publicstaticvoid main (String [] args) {
Foo reallyABar = new Bar(); // Legal because Bar is a
// subclass of Foo
Bar reallyAFoo = new Foo(); // Illegal! Foo is not a
// subclass of Bar
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from Foo to Bar
at MainClass.main(MainClass.java:11)