以“this”作为参数的Java构造函数

问题描述 投票:0回答:1

我是 Java 的绝对初学者,过去 6 天我一直在使用 Roger Caldenhead 的书和 geeksforgeeks.org/java 来熟悉这门语言。我一直在试图理解这个关键字。在极客网站上,我注意到以下几点:

class B {
    int x = 5;

    // Default Constructor that create an object of A
    // with passing this as an argument in the
    // constructor
    B() { A obj = new A(this); }

请问有人可以告诉我 THIS 作为 new A(this) 中的参数是否引用属于 A 类或 B 类的对象吗?我确实明白,A类的对象正在内存堆中创建,并且该对象被传递给A类的引用变量。但是参数THIS到底表示什么,它表示A类的对象还是B 类对象? geeksforgeeks 和 Caldenhead 书中的评论并没有使这一点变得清晰。

java class this keyword
1个回答
0
投票

使用 this 关键字中的文档说

在实例方法或构造函数中,

this
是对 当前对象。

因此

this
指的是代码中的
B
类。

© www.soinside.com 2019 - 2024. All rights reserved.