public class Downcast {
public static void main(String[] args) {
Base[] b = {
new Base(),
new Derived()
};
m(b[1]);
System.out.println("-----");
m(b[0]);
}
public static void m(Base b) {
b.f();
b.g();
// the following is illegal.
// b.z();
// Downcasting
((Derived)b).z();
}
}
class Base {
public void f() {
System.out.println("Base.f()");
}
public void g() {
System.out.println("Base.g()");
}
}
class Derived extends Base {
public void f() {
System.out.println("Derived.f()");
}
public void g() {
System.out.println("Derived.g()");
}
public void z() {
System.out.println("Derived.z()");
}
}
Downcast.java output
Derived.f()
Derived.g()
Derived.z()
-----
Base.f()
Base.g()
Exception in thread "main" java.lang.ClassCastException: Base
at Downcast.m(Downcast.java:18)
at Downcast.main(Downcast.java:7)
Tag: Study Code Program Java
No comments:
Post a Comment