加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 与构造函数和子类混淆

发布时间:2020-12-15 04:42:29 所属栏目:Java 来源:网络整理
导读:我无法理解使用带子类的构造函数的概念. 这是父类: public class A{ public A() { System.out.println("The default constructor of A is invoked"); }} 儿童班: public class B extends A{ public B(String s) { System.out.println(s); }} 而我的主要方
我无法理解使用带子类的构造函数的概念.

这是父类:

public class A
{
    public A()
    {
        System.out.println("The default constructor of A is invoked");
    }
}

儿童班:

public class B extends A
{
    public B(String s)
    {
        System.out.println(s);
    }
}

而我的主要方法是:

public class C
{
    public static void main (String[] args)
    {
        B b = new B("The constructor of B is invoked");
    }
}

当我运行C时,我得到的输出是

The default constructor of A is invoked

The constructor of B is invoked

我不明白的是为什么来自A类的消息正在输出.因为你将一个字符串参数传递给B类的构造函数,它不应该只打印出来吗?换句话说,输出不应该只是:

The constructor of B is invoked

在此先感谢,我真的很感谢你们给予的任何帮助.

解决方法

从 docs

If a constructor does not explicitly invoke a superclass constructor,the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor,you will get a compile-time error. Object does have such a constructor,so if Object is the only superclass,there is no problem.

因此,即使您没有显式调用超类构造函数,编译器也会在类B的构造函数中插入名为super()的语句.

这就是B类构造函数在编译后的样子.

public B(String s){
    super(); // this is inserted by the compiler,if you hadn't done it yourself.
    System.out.println(s);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读