Java继承类对象的创建


Java中,构造器负责创建特定类的对象。除了构造器的其他功能外,它还实例化其类的属性/实例。在Java中,默认情况下,super()关键字用作每个类的构造器的第一行,此方法的目的是调用其父类的构造器,以便在其子类继承并使用之前,其父类的属性得到正确的实例化。

这里需要注意的是,当您创建对象时会调用构造器,但这并不意味着每当您调用类的构造器时都会创建该类的对象。如上例所示,从子类的构造器中调用父类的构造器,但只创建子类的对象,因为子类与其父类之间存在is-a关系。

创建继承类对象的步骤

以下是Java继承类对象创建的步骤:

  • 首先,我们将创建一个父类,该父类具有一个输出类名和消息的构造器。
  • 我们将在子类中定义父类的扩展。
  • 在子类中包含一个输出类名和消息的构造器。
  • 在主程序中创建一个子类对象。注意,在父类构造器之后调用子类构造器。
  • 通过运行应用程序并观察输出,验证父类构造器在子类构造器之前被调用。

创建继承类对象的Java程序

以下是Java继承类对象创建的Java程序:

class InheritanceObjectCreationParent {
    public InheritanceObjectCreationParent() {
        System.out.println("parent class constructor called..");
        System.out.println(this.getClass().getName()); //to know the class of which object is created.
    }
}
public class InheritanceObjectCreation extends InheritanceObjectCreationParent {
    public InheritanceObjectCreation() {
        //here we do not explicitly call super() method but at runtime complier call parent class constructor
        //by adding super() method at first line of this constructor.
        System.out.println("subclass constructor called..");
        System.out.println(this.getClass().getName()); //to know the class of which object is created.
    }
    public static void main(String[] args) {
        InheritanceObjectCreation obj = new InheritanceObjectCreation(); // object creation.
    }
}

输出

parent class constructor called..
InheritanceObjectCreation
subclass constructor called..
InheritanceObjectCreation

代码解释

在这个Java程序中,我们将创建一个父类`InheritanceObjectCreationParent`,它带有一个打印消息和类名的构造器。现在我们可以看到,子类`InheritanceObjectCreation`扩展了父类,并且还有一个输出类名和消息的构造器。虽然我们没有特别调用`super()`关键字,但Java编译器会在创建子类对象时自动调用父类构造器。通过这样做,可以确保父类构造器首先初始化父类属性,在子类构造器之前运行。

更新于:2024年8月22日

2K+浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.