I'm a beginner in language, so please let me know when Super is called automatically.

Asked 1 years ago, Updated 1 years ago, 68 views

I have a question about the program below, why isn't the superclass constructor called automatically when the sixth line of the Child class constructor is called?

What I've tried so far:

  • Read the commentary
  • On Eclipse, type the code.

Additional
The output is ABCD, but why isn't it ABCD?

class Parent {
    public Parent() {
        System.out.println("A");
    }
    public Parent (String value) {
        this();
        System.out.println(val);
    }
}

class Child extensions Parent {
    publicChild(){
        super("B");
        System.out.println("C");
    }
    public Child (String value) {
        this();
        System.out.println(val);
    }
}

public class Main {
    public static void main(String[]args) {
        new Child("D");
    }
}

Enter a description of the image here

java java8

2022-09-30 20:16

1 Answers

First of all, if you don't explicitly call the implicit constructor in the child class forces the parent constructor with no arguments to call.I'll get caught.
With the above in mind, Fabian's question is interpreted as "Why is Child(Stringval) only calling this(); implicitly calling a parent constructor without arguments?"
Certainly, if an explicit constructor call occurs after an implicit constructor call, the output will be AAA BCD 」.

The Subclass Constructors in the Oracle document reads as though it does not mention the super(); call by the constructor chain for those who have implicit constructor calls.
(Maybe it's just my poor English reading ability...)

In the end, if you only call the parent constructor somewhere in the constructor chain, there will be no implicit constructor calls.
This is a very confusing statement, but it is written at the end of the Oracle document 8.8.7.1.Explicit Constructor Invocations.( 8.8.8. Constructor Overloading section immediately preceding)

Execution of instance variable initializers and instance initializers is performed regardless of which the superclass constructor invocation actual applications as an explicit constructor invocation statement or is provisioned automatically.(Anternate constructor invocation does not appear.)

The parent constructor invocation process clearly states that no implicit invocation will occur if super(); is called somewhere, even if it is presented automatically by the constructor chain.
This specification results in "AB CD" output.


2022-09-30 20:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.