当前位置: 代码迷 >> Java相关 >> 有件事实在弄不明白高手指点下~~
  详细解决方案

有件事实在弄不明白高手指点下~~

热度:125   发布时间:2005-09-17 20:46:00.0
有件事实在弄不明白高手指点下~~
B是A的 子类

那么这么定义是什么意思啊

A a = new B()
----------------解决方案--------------------------------------------------------
向上转型
----------------解决方案--------------------------------------------------------
class A


{


  int a = 2;


  public void display()


  {


    System.out.println(a);


  }


}





class B extends A


{


  int b;


  public B()


  {


    b = a+1;


  }


  public void display()


  {


    System.out.println(b);


  }


}





class InheritanceDemo


{


  public static void main(String [] args)


  {


    A a = new B();  // it is ok


    a.display();


   


    // let's try another way


    // you will find, it is wrong


    B b = new A();  // wrong code  ,  将这两行屏蔽掉,然后再试


    b.display();    // so this b does not exist





    // and now we try a normal way


    A anotherA = new A();


    anotherA.display();





    // and we try this normal way


    B anotherB = new B();


    anotherB.display();


  }


}
----------------解决方案--------------------------------------------------------
谢谢
----------------解决方案--------------------------------------------------------
  相关解决方案