日期:2014-05-20  浏览次数:20566 次

请各位大神解释下一段代码
public class two extends A{
int fun2() {
        return 456;
}

public static void main(String[] args) {
  two b = new two();
          b.fun1();
          A a = b;
          a.fun1();

}

}
class A {
    void fun1() {
          System.out.println(fun2());
    }

    int fun2() {
            return 123;
    }
}

------解决方案--------------------
都是456, 都是调用的class two 的fun2方法, 因为实例都是class two的实例

b.fun1() 这是继承了A的方法,就相当于在class two 里面这么写
public class two extends A{
    int fun2() {
        return 456;
    }
   int fun1() {
    System.out.println(fun2());
  } 
 所以会打印出456

第二个,虽然这个变量声明的A 类,但是指向的却是two 类, 所以也会打印出456。 需要注意的是 a 只可以执行 two 从 A 里继承的方法,而不能执行two自己定义的方法