题目出的有点纰漏,纠正一下。
| java代码: |
|
Child c= new Child ( ) ; Parent p=c; p. print ( ) ; c. print ( ) ; |
新建Child实例c,然后将c赋予指向Child祖先Parent的变量p,然后分别调用p.print() c.print(),打印结果却各不相同。
Parent类print()中的代码为:System.out.println("parent");
Child类print()中的代码为:System.out.println("child");
执行结果:
parent
child
这和多态的原则冲突,谁知道答案呢?
更不敢揭晓了,还是和你单挑比较划算, -..=
代码如下,仔细看看变知究竟:
| java代码: |
|
package parent; import child. Child ; public class Parent { void print ( ) { System . out . println ( "Parent" ) ; } public static void main ( String [ ] args ) { Child c= new Child ( ) ; Parent p=c; p. print ( ) ; c. print ( ) ; } } |
| java代码: |
|
package child; import parent. Parent ; public class Child extends Parent { public void print ( ) { System . out . println ( "Child" ) ; } } |
|
| |
| 当方法不写作用域的时候,默认为friendly,而friendly的作用域只局限域同一个包内,对于子孙类,就超出她的作用域了,所以,这个不是Override了。 | |

925

被折叠的 条评论
为什么被折叠?



