题目
下列代码的输出结果是 。 class Parent( void printMe() { System.out.println("parent"); ) } class Child extends Parent ( void printMe() { System.out.println("child"); ) void printall() ( super.printMe(); this.printMe(); printMe(); ) } public class Test_this ( public static void main(String args[]) { Child myC=new Child(); myC.printall(); ) }
下列代码的输出结果是 。 class Parent{ void printMe() { System.out.println("parent"); } } class Child extends Parent { void printMe() { System.out.println("child"); } void printall() { super.printMe(); this.printMe(); printMe(); } } public class Test_this { public static void main(String args[]) { Child myC=new Child(); myC.printall(); } }
题目解答
答案
parent child child
解析
步骤 1:定义父类 Parent
在父类 Parent 中定义了一个方法 printMe(),该方法输出 "parent"。
步骤 2:定义子类 Child
子类 Child 继承自父类 Parent,并重写了父类的 printMe() 方法,使其输出 "child"。同时,子类 Child 中定义了一个方法 printall(),该方法调用了父类的 printMe() 方法、子类的 printMe() 方法以及直接调用 printMe() 方法。
步骤 3:执行 main 方法
在 main 方法中,创建了一个 Child 类的实例 myC,并调用了其 printall() 方法。
步骤 4:执行 printall 方法
在 printall 方法中,首先调用 super.printMe(),即调用父类的 printMe() 方法,输出 "parent"。然后调用 this.printMe(),即调用子类的 printMe() 方法,输出 "child"。最后直接调用 printMe() 方法,由于在子类中重写了父类的 printMe() 方法,因此输出 "child"。
在父类 Parent 中定义了一个方法 printMe(),该方法输出 "parent"。
步骤 2:定义子类 Child
子类 Child 继承自父类 Parent,并重写了父类的 printMe() 方法,使其输出 "child"。同时,子类 Child 中定义了一个方法 printall(),该方法调用了父类的 printMe() 方法、子类的 printMe() 方法以及直接调用 printMe() 方法。
步骤 3:执行 main 方法
在 main 方法中,创建了一个 Child 类的实例 myC,并调用了其 printall() 方法。
步骤 4:执行 printall 方法
在 printall 方法中,首先调用 super.printMe(),即调用父类的 printMe() 方法,输出 "parent"。然后调用 this.printMe(),即调用子类的 printMe() 方法,输出 "child"。最后直接调用 printMe() 方法,由于在子类中重写了父类的 printMe() 方法,因此输出 "child"。