Parent p = new Child();        //这里我没有明白 这样可以么? 我运运行了,可以,但是请给我解释一下,为什么 好么?class Parent {
public Parent () {
System.out.println("Initialising a Parent");
}
public void foo () {
System.out.println("Parent's foo");
}
public void bar () {
System.out.println("Parent's bar");
}
}
public class Child extends Parent {
public Child () {
System.out.println("Initialising a Child");
}
public void foo () {
System.out.println("Child's foo");
}
public void bar () {
System.out.println("Child's bar");
super.bar();
}
public static void main (String[] args) {
// INSERT STATEMENTS HERE
}
}
==========================================================
For each of the following question parts, you must write the output
produced by inserting the shown program statements into the main
method of class Child at the location shown.
(a) [ 5 s ]
    Parent p = new Parent();
    p.foo();
    Child c = new Child();
    c.foo();
(b) [ 5 s ]
    Parent p = new Child();        //这里我没有明白 这样可以么? 我运运行了,可以,但是请给我解释一下,为什么 好么?
    p.foo();
    p.bar();

解决方案 »

  1.   

     Parent p = new Child();  
    我不明白的地方是。 这样 定义,事实上是定义了那个类?
    作用是什么?
      

  2.   

    这样的问题CSDN中太多了,
    你可以去已解决的版块看看
      

  3.   

    这里用的Java的多态性,申明变量为父类,但指向其子类,创建子类的实例。
    如果子类重写了父类的方法,像这里的foo()和bar(),那么运行的其实是子类的方法。
      

  4.   

    因为Child继承了Parent。
    Parent p = new Child(); 意思是创建一个Child对象,并将其作为Parent对象使用。这样就不用在意Child与Parent的区别了。不知道这么说是否准确举个例子:
    class 鼠标 {
       public String getCount() {
          return "一般鼠标有两个按键";
       }   ....其他方法....
    }class 三建鼠标 extends 鼠标 {
        public String getCount() {
             return "该鼠标有三个按键";
        }
    }鼠标 mouse = new 三建鼠标();
    mouse.getCount();    //返回"该鼠标有三个按键"。
    可能还有“4建鼠标”,但你使用时不关心他是什么样的鼠标,只要她是鼠标就成。
      

  5.   

    Parent p = new Child(); 没问题
    public class Child extends Parent 说明child继承了parent类。
    p实际上还是Parent 的对象,但是是Child的实例,所以调用的方法都是Child的,输出是这样的:
    -------------------------------------------
    Initialising a Parent
    Initialising a Child
    Child's foo
    Child's bar
    Parent's bar
    ----------------------------------------
    首先Parent p = new Child(); 调用父类Parent 的构造方法
    输出Initialising a Parent
    再调用其子类的Child()构造方法。
    super.bar();调用超类(其父类)的bar()方法,所以最后一条有
    Parent's bar