06-继承与多态(动手动脑与验证)

一、继承条件下构造方法的调用

测试代码一:

 1 class Grandparent 
 2 {
 3     public Grandparent()
 4      {
 5             System.out.println("GrandParent Created.");    
 6 }
 7     public Grandparent(String string) 
 8     {
 9             System.out.println("GrandParent Created.String:" + string);
10     }
11 }
12 
13 class Parent extends Grandparent
14 {
15     public Parent()
16     {
17             //super("Hello.Grandparent.");
18             System.out.println("Parent Created");    
19             // super("Hello.Grandparent.");
20     }
21 }

测试结果:

测试代码二:

 1 class Grandparent 
 2 {
 3     public Grandparent()
 4      {
 5             System.out.println("GrandParent Created.");    
 6 }
 7     public Grandparent(String string) 
 8     {
 9             System.out.println("GrandParent Created.String:" + string);
10     }
11 }
12 
13 class Parent extends Grandparent
14 {
15     public Parent()
16     {
17             super("Hello.Grandparent.");
18             System.out.println("Parent Created");    
19             // super("Hello.Grandparent.");
20     }
21 }

测试结果:

测试代码三:

 1 //编译错误
 2 class Grandparent 
 3 {
 4     public Grandparent()
 5      {
 6             System.out.println("GrandParent Created.");    
 7 }
 8     public Grandparent(String string) 
 9     {
10             System.out.println("GrandParent Created.String:" + string);
11     }
12 }
13 
14 class Parent extends Grandparent
15 {
16     public Parent()
17     {
18             //super("Hello.Grandparent.");
19             System.out.println("Parent Created");    
20             super("Hello.Grandparent.");        //报错
21     }
22 }    

测试结果:

(构造函数调用必须在构造函数第一条语句)

结论:子类的构造方法在运行之前,必须调用父类的构造方法。

原因:构造函数的作用为初始化,当被继承的父类未初始化时,无法生成子类对象。

二、ParentChildTest

程序代码:

 1 package ParentChild;
 2 public class ParentChildTest {
 3     public static void main(String[] args) {
 4         Parent parent=new Parent();
 5         parent.printValue();
 6         Child child=new Child();
 7         child.printValue();
 8         
 9         parent=child;
10         parent.printValue();
11         
12         parent.myValue++;
13         parent.printValue();
14         
15         ((Child)parent).myValue++;
16         parent.printValue();
17         
18     }
19 }
20 
21 class Parent{
22     public int myValue=100;
23     public void printValue() {
24         System.out.println("Parent.printValue(),myValue="+myValue);
25     }
26 }
27 class Child extends Parent{
28     public int myValue=200;
29     public void printValue() {
30         System.out.println("Child.printValue(),myValue="+myValue);
31     }
32 }

预测输出结果:

实际执行结果:

原因分析:

  当子类与父类具有相同名称的成员时,调用子类对象,默认调用的是子类中的成员,即父类同名成员被隐藏。

  当父类变量引用一个子类对象时,使用父类还是子类成员,由对象自己的“真实”类型所决定

原文地址:https://www.cnblogs.com/lzq666/p/7816640.html