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 }
    复制代码
  • 相关阅读:
    ant的安装和配置
    jmeter3.x的jtx文件解析
    爬虫:网页里元素的xpath结构,scrapy不一定就找的到
    如何实现新浪微博功能:关注某个的发布信息,自动点赞和转发
    性能测试各个指标的含义
    python模块相关
    curl的用法
    第十八章 Python批量管理主机(paramiko、fabric与pexpect)
    死锁产生的原因和解锁的方法
    读写分离死锁解决方案、事务发布死锁解决方案、发布订阅死锁解决方案
  • 原文地址:https://www.cnblogs.com/du1269038969/p/6053867.html
Copyright © 2011-2022 走看看