在java中调用构造函数 [英] invoking constructor in java

查看:74
本文介绍了在java中调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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. ?

推荐答案

不,答案是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).

这篇关于在java中调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆