zoukankan      html  css  js  c++  java
  • 接口与继承

    一、神奇的+号

    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 }
    复制代码

    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 }
    复制代码
  • 相关阅读:
    Programming In Lua 第一章
    TCP/IP 第四、五章
    wireshark数据包分析实战 第三、四章
    [MFC.Windows程序设计(第2版) 第一章
    wireshark数据包分析实战 第二章
    C++PrimerPlus第6版 第四章——复合类型
    TCP/IP 第三章
    Linux命令行与脚本编程大全第一章
    Flink的并行度设置
    基于HttpClient的工具类HttpUtil
  • 原文地址:https://www.cnblogs.com/du1269038969/p/6053867.html
Copyright © 2011-2022 走看看