对象类型的强制转换

public class Base {
 public static final String FOO = "foo";
 public static void main(String[] args) {
  Base b = new Base();
  Sub s = new Sub();
  System.out.print(Base.FOO);
  System.out.print(Sub.FOO);
  System.out.print(b.FOO);
  System.out.print(s.FOO);
  System.out.print(((Base) s).FOO); // 把s对象强制转换为 Base 类型
 }
}
class Sub extends Base {
 public static final String FOO = "bar";
}

输出:

foobarfoobarfoo

System.out.print(); // 输出语句

(Base) s // 把s对象强制转换为 Base 类型

((Base) s).FOO // 获取s对象的 FOO成员属性

posted @ 2018-08-23 11:04  闻长歌而知雅意  阅读(811)  评论(0编辑  收藏  举报