A类:packagea.b;publicclassA{voidaMthod(){System.out.println("Amethod");}}A的子类B:packagea.b;publicclassBextendsA{voidbMethod1(){System.out.println("Bmethod1");}voidbMe...
A类: package a.b; public class A { void aMthod() { System.out.println("A method"); } } A的子类B: package a.b; public class B extends A { void bMethod1() { System.out.println("B method 1"); } void bMethod2() { System.out.println("B method 2"); } } C类: package a.b; public class C { public static void main(String[] args) { A a1 = new B(); // 向上转型 a1.aMthod(); // 调用父类aMthod(),a1遗失B类方法bMethod1()、bMethod2() B b1 = (B) a1; // 向下转型,编译无错误,运行时无错误 b1.aMthod(); // 调用父类A方法 b1.bMethod1(); // 调用B类方法 b1.bMethod2(); // 调用B类方法 A a2 = new A();
// 向下转型,编译无错误,运行时将出错 b2.aMthod(); b2.bMethod1(); b2.bMethod2(); } }
展开