gpt4 book ai didi

java - 创建子类时父类(super class)打印意外值

转载 作者:行者123 更新时间:2023-12-02 02:26:19 24 4
gpt4 key购买 nike

您能否帮助理解以下java代码的输出,其中 this(0)Superclass当为 Subclass 创建对象时调用.

在此代码中,尽管代码中没有提及显式打印 20 ,为什么第一个值打印为 20

class Superclass {
Superclass() {
this(0);
System.out.println("1");
}

Superclass(int x) {
System.out.println("2" + x);
}
}

class Subclass extends Superclass {
Subclass(int x) {
System.out.println("3" + x);
}

Subclass(int x, int y) {
System.out.println("4" + x + y);
}
}

public class practiceTest {
public static void main(String[] args) {
Subclass s = new Subclass(10, 20);
}
}

最佳答案

字符串加法

In this code though there is no mention in the code to explicitly print "20"

实际上是有的,看看你的父类(super class)

Superclass() {
this(0);
System.out.println("1");
}

Superclass(int x) {
System.out.println("2" + x);
}

字符串的加法被解释为串联,而不是普通的加法(值)。因此,调用 Superclass 的默认构造函数会触发 this(0) 并产生

    System.out.println("2" + x);
=> System.out.println("2" + 0);
=> System.out.println("20");

因此打印20

<小时/>

整数加法

如果您想将值添加为整数,则需要使用int值而不是String值,例如像

Superclass(int x) {
System.out.println(2 + x);
}

那么你也会得到

    System.out.println(2 + x);
=> System.out.println(2 + 0);
=> System.out.println(2);
<小时/>

构造函数链

好吧,如果你打电话到底会发生什么

Subclass s = new Subclass(10, 20);

好吧,首先,当然,你触发这个构造函数

Subclass(int x, int y) {
System.out.println("4" + x + y);
}

现在在 Java 中,创建子类时,您总是需要调用父类(super class)的构造函数之一(根据语言的定义)。

如果您没有显式指定此类调用,那么它会尝试调用父类(super class)的默认构造函数。如果没有,则无法编译。但是,您有这样一个默认构造函数,因此代码将相当于

Subclass(int x, int y) {
// Implicit call of default super-constructor
super();
System.out.println("4" + x + y);
}

所以你调用以下构造函数

Superclass() {
this(0);
System.out.println("1");
}

如上所示,触发另一个构造函数

Superclass(int x) {
System.out.println("2" + x);
}

因此,如果解析此链,您将得到以下输出

// from Superclass(int x)
System.out.println("2" + 0);
// from Superclass()
System.out.println("1");
// from Subclass(int x, int y)
System.out.println("4" + 10 + 20);

产生

20
1
41020

关于java - 创建子类时父类(super class)打印意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47728890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com