首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

请诸位大神解释下一段代码

2013-07-01 
请各位大神解释下一段代码public class two extends A{int fun2() {return 456}public static void main(

请各位大神解释下一段代码

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自己定义的方法

热点排行