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

super 要点

时间:2015-11-08 22:05:25      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:


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("Hello.Grandparent.");
        System.out.println("Parent Created");
        //super("Hello.Grandparent.");
    }
}
class Child extends Parent
{
    public Child()
    {
        System.out.println("Child Created");
    }
}
public class TestInherists {
    public static void main(String args[])
    {
        Child c=new Child();
    }
}

结果截图:

技术分享

若把上面绿色注释取消,如下

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

就会报错

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

this 和 super有区别,this用于此类,而super用于父类,若没写super,系统将默认进行super,若写了,则必须放在第一个语句

super 要点

标签:

原文地址:http://www.cnblogs.com/cchjl/p/4948127.html

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