java 在java中调用构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13805191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
invoking constructor in java
提问by Ravi
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();
}
}
Question starts from one Interview Question (what happens when an object is created in Java?)
问题从一个面试问题开始(用 Java 创建对象时会发生什么?)
and answer is...
答案是……
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.
调用最派生类的构造函数。构造函数所做的第一件事是为其超类调用构造函数。这个过程一直持续到 java.lang.Object 的构造器被调用为止,因为 java.lang.Object 是 java 中所有对象的基类。在执行构造函数体之前,会执行所有实例变量初始化器和初始化块。然后执行构造函数的主体。因此,基类的构造函数最先完成,派生程度最高的类的构造函数最后完成。
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. ?
所以,根据上面的说法,答案应该是ABCC,但它只显示ABC。虽然,当我评论super()
派生构造函数时。然后,输出是ABC。请帮我弄清楚,我是否误解了上面的段落。?
回答by PermGenError
No, the answer is ABC
不,答案是ABC
My m = new My();
The above firstinvokes 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`.
上面首先调用My class
,然后对其超类(即 C Class')进行超级调用,然后对'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`进行超级调用。
Thus the answer is ABC
因此答案是ABC
EDIT:
编辑:
You dont really need to explicitlycall super()
in your My Class
as it'd be included by the compilerunless you call an overloaded constructor
of that class like 'this(something)'
你真的不需要显式调用super()
你的,My Class
因为它会被编译器包含,除非你调用一个overloaded constructor
类'this(something)'
回答by Bhavik Ambani
The below code will print ABC
下面的代码将打印 ABC
To invoke the constructor of the super class, the compiler will implicitly call the super()
in each and every class extending the class, if you are not calling the super
construcotr explicitly.
要调用超类的构造函数,编译器将super()
在每个扩展类的类中隐式调用,如果您没有super
显式调用构造函数。