Java中的继承 - 创建子类的对象还调用超类的构造函数。为什么? [英] Inheritance in Java - creating an object of the subclass invokes also the constructor of the superclass. Why exactly?

查看:127
本文介绍了Java中的继承 - 创建子类的对象还调用超类的构造函数。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于Java中继承的问题。



我有两个类 A B 和B类继承:A:

  public class A {
public A(){
System.out.println(Hi!);
}
}


public class B extends A {
public B(){
System.out.println(Bye! );
}

public static void main(String [] args){
B b = new B();
}
}

当我运行程序B时,输出是: / p>

 嗨! 
Bye!




问题:为什么当创建类B 的对象时,会调用类A 的构造函数


我知道B继承一切从A所有的实例或类变量和所有的方法,在这个意义上B的对象具有A的所有特性加上B中定义的一些其他特性。然而,我不知道,没有想象,当我创建一个类型B的对象,A的构造函数也被调用。
所以,写这个:

  B b = new B 

创建两个对象 - 类型B和类型A之一



这很有意思,



有人可以解释为什么会发生这种情况吗?

解决方案

它不创建两个对象,只有一个: B 。 b
$ b

从另一个类继承时,必须在构造函数中调用super()。如果你不这样做,编译器会为你插入这个调用,你可以清楚地看到。



超类构造函数被调用,否则对象将保留在未初始化



在编译器插入超级调用之后,您的子类实际上如下所示:

  public class B extends A {
public B(){
super();
System.out.println(Bye!);
}
}


I have a question about inheritance in Java.

I have two classes A and B , and class B, inherits from A:

public class A {
     public A() {
         System.out.println("Hi!");
     }
}


public class B extends A {
     public B() {
         System.out.println("Bye!");
     }

     public static void main(String[] args) {
         B b = new B();
     }
}

When I run program B, the output is:

Hi!
Bye!

Question : why the constructor of class A is invoked, when I create and object of class B ?

I know that B inherits everything from A - all instance or class variables, and all methods, and in this sense an object of B has all characteristics of A plus some other characteristics defined in B. However, I didn't know and didn't imagine that when I create an object of type B, the constructor of A is also invoked. So, writing this:

B b = new B();

creates Two objects - one of type B, and one of type A.

This is getting interesting,

can somebody explain why exactly this happens?

解决方案

It doesn't create two objects, only one: B.

When inheriting from another class, you must call super() in your constructor. If you don't, the compiler will insert that call for you as you can plainly see.

The superclass constructors are called because otherwise the object would be left in an uninitialized state, possibly unbeknownst to the developer of the subclass.

Your subclass actually looks like this after the compiler inserts the super call:

public class B extends A {
    public B() {
        super();
        System.out.println("Bye!");
    }
}

这篇关于Java中的继承 - 创建子类的对象还调用超类的构造函数。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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