码迷,mamicode.com
首页 > 其他好文 > 详细

07 继承与接口

时间:2016-11-10 23:49:13      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:观察   new   运行   影响   ring   image   继承   void   访问   

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

1、运行 TestInherits.java 示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,注意这句调用代码是否是第一句,影响重大!

源代码:

package lianxi7;

class GrandParent
{

    public GrandParent()
    {
        System.out.println("GrandParent Created");
    }

    public GrandParent(String string)
    {
        System.out.println("GrandParent Created.String:"+string);
    }

}

class Parent extends GrandParent{
    public Parent(){
        super("sdg");
        
        System.out.println("Parent Created");
        
    }
}

class Child extends Parent{
    public Child(){
        
        System.out.println("Child Created");
    }
}
public class TestInherits {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Child c=new Child();
    }
}

实验结果截图:

技术分享

 

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

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

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

二、神奇的“+”号

技术分享

注意最后一句,一个字串和一个对象“相加”,得到以下结果:

技术分享

在“+”运算中,当任何一个对象与一个String对象,连接时,会隐式地调用其toString()方法,默认情况下,此方法返回“类名 @ + hashCode”。为了返回有意义的信息,子类可以重写toString()方法。

三、请自行编写代码测试以下特性: 在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

源代码:

class GrandParent
{

    public GrandParent()
    {
        System.out.println("GrandParent Created");
    }

    public GrandParent(String string)
    {
        System.out.println("GrandParent Created.String:"+string);
    }

}

class Parent extends GrandParent{
    public Parent(){
        super("sdg");
        
        System.out.println("Parent Created");
        
    }
}

class Child extends Parent{
    public Child(){
        
        System.out.println("Child Created");
    }
}
public class TestInherits {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Child c=new Child();
    }
}

实验截图为:

技术分享

未添加super("sdg")之前的结果:

技术分享

 

07 继承与接口

标签:观察   new   运行   影响   ring   image   继承   void   访问   

原文地址:http://www.cnblogs.com/610553824lyx/p/6052474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!