课堂作业(接口与继承)

 一、神奇的+号

1)源代码:

 1 public class Fruit
 2 {
 3     public String toString()
 4     {
 5         return "Fruit toString.";
 6     }
 7 
 8     public static void main(String args[])
 9     {
10         Fruit f=new Fruit();
11         System.out.println("f="+f);
12         System.out.println("f="+f.toString());
13     }
14 }

2)结果截图:

3)结果分析:

注意倒数第二句,一个字串和一个对象“相加”,得到以下结果?

 Fruit类覆盖了Object类的toString方法。在“+”运算中,当任何一个对象与一个String对象,连接时,会隐式地调用其toString()方法,默认情况下,此方法返回“类名 @ + hashCode”。

为了返回有意义的信息,子类可以重写toString()方法。

二、动手实验:继承条件下的构造方法调用

1)源代码:

 1 public class TestInherits {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5 
 6         Child c = new Child();
 7     }
 8 
 9 }
10 
11 class GrandParent
12 {
13     public GrandParent()
14     {
15         System.out.println("GrandParent Created.Sting:");
16     }
17     public GrandParent(String string)
18     {
19         System.out.println("GrandParent Created.Sting...:" + string);
20     }
21 }
22 
23 class Parent extends GrandParent
24 {
25     public Parent()
26     {  
27         super("mk");
28         System.out.println("Parent Created");
29         //super("Hello.GrandParent");
30     }
31 }
32 
33 class Child extends Parent
34 {
35     public Child()
36     {
37         System.out.println("Child Created");
38     }
39 }

2)结果截图:
      

3)结果分析:

通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

4)为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能反过来?

不能反过来。子类是通过父类继承过来的,所以子类有父类的属性和方法,如果不调用父类的构造方法,不能初始化父类中定义的属性,即不能给父类的属性分配内存空间 ,如果父类的属性没有分配内存空间,那么子类访问父类的属性,就会报错。 

三、动手动脑 在子类中,若要调用父类中被覆盖的方法,可以使用super关键字?

1)源代码:

 1 public class fugaiSuper {
 2     public static void main(String[] args) {
 3 
 4         Child c = new Child();
 5         c.showMessage();
 6     }
 7 }
 8 
 9 class Parent
10 {
11     public void showMessage()
12     {
13         System.out.println("parent!");
14     }
15 }
16 
17 class Child extends Parent
18 {
19     public void showMessage()
20     {   
21         System.out.println("child!");
22         super.showMessage();
23     }
24 }
原文地址:https://www.cnblogs.com/ghs1065248758/p/6053771.html