• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在java调用构造函数

用户头像
it1352
帮助1

问题说明

class A {

    A() {
        System.out.print("A");
    }
}

class B extends A {
     B() {
        System.out.print("B");
    }
}

class C extends B {
 C() {
        System.out.print("C");
    }
}

public class My extends C {
My(){
super();
}
    public static void main(String[] args) {
        My m = new My();
    }
}

问题从一个面试问题开始(用 Java 创建对象时会发生什么?)

Question starts from one Interview Question (what happens when an object is created in Java?)

答案是...

调用最派生类的构造函数.第一个构造函数所做的事情是为其调用构造函数超类.这个过程一直持续到构造器java.lang.Object 被调用,因为 java.lang.Object 是java中的所有对象.在构造函数体执行之前,所有实例变量初始化器和初始化块都是执行.然后执行构造函数的主体.因此,基类的构造函数首先完成,而基类的构造函数完成大多数派生类最后完成.

The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

所以,根据上面的说法,答案应该是ABCC,但它只显示ABC.虽然,当我在派生构造函数中注释 super() 时.然后,输出是ABC.请帮我弄清楚,我是否误解了上面的段落.?

So, according to above statement, answer should be ABCC, but it showing only ABC. Although, when i'm commenting the super() in derived constructor. Then, output is ABC. Please, help me to figure out, did i misunderstand the above paragraph. ?

正确答案

#1

不,答案是ABC

My m = new My(); 

上述首先调用My类,然后对其超类即C类进行超级调用,然后进行超级调用到 B 类,然后对 A 类进行超级调用,然后对 java.lang.Object 进行超级调用,因为所有对象都扩展 <代码>java.lang.Object.

The above first invokes My class, then a super call is made to its super class i.e., C class, then a super call to B class is made, then a super call to A Class, then a Super call to java.lang.Object as all objects extend java.lang.Object.

因此答案是ABC.

您真的不需要显式在您的 My 类中调用 super(),因为它会包含在 >compiler 除非您调用该类的重载构造函数,例如 this(something).

You don't really need to explicitly call super() in your My class as it'd be included by the compiler unless you call an overloaded constructor of that class like this(something).

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfgchg
系列文章
更多 icon
同类精品
更多 icon
继续加载