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

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

问题描述

我有一个关于 Java 继承的问题.

我有两个类 AB 和类 B,继承自 A:

公共类 A {公共 A() {System.out.println("嗨!");}}公共类 B 扩展 A {公共 B() {System.out.println("再见!");}公共静态无效主(字符串 [] args){B b = 新 B();}}

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

嗨!再见!

<块引用>

问题:当我创建class B的对象时,为什么会调用class Aconstructor?

我知道 B 继承了 A 的所有内容——所有实例或类变量,以及所有方法,从这个意义上说,B 的对象具有 A 的所有特征以及 B 中定义的一些其他特征.但是,我不知道并没有想到,当我创建一个类型B的对象时,A的构造函数也被调用了.所以,写这个:

B b = new B();

创建两个对象 - 一个类型 B,一个类型 A.

越来越有趣了,

有人能解释一下为什么会发生这种情况吗?

解决方案

它不会创建两个对象,只有一个:B.

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

调用超类构造函数是因为否则对象将处于未初始化状态,子类的开发人员可能不知道.

在编译器插入 super 调用后,您的子类实际上是这样的:

public class B extends A {公共 B() {极好的();System.out.println("再见!");}}

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天全站免登陆