有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么在Java中将“this”用作方法参数时会收到此错误消息?

我最近读到this是一个局部变量,它包含当前对象的引用ID,可以在任何实例函数中使用。但是,当我显式地将this声明为int参数时,我得到的编译时错误是:“接收方类型与封闭类类型不匹配”

class ThisDemo
{
    void show(int this)
    {
        System.out.println(this);
    }
}
class ThisDemo1
{
    public static void main(String... s)
    {
        ThisDemo a=new ThisDemo();
        int x=10;
        a.show(x);
    }
}

共 (3) 个答案

  1. # 1 楼答案

    不能使用this命名变量,因为它在Java中是保留关键字this指的是您当前的对象(在您的例子中是类ThisDemo的对象)。我想你想要达到以下目标:

    class ThisDemo
    {
        void show()
        {
            System.out.println(this);
        }
    }
    class ThisDemo1
    {
        public static void main(String... s)
        {
            ThisDemo a=new ThisDemo();
            a.show();
        }
    }
    
  2. # 2 楼答案

    您可能会被错误消息弄糊涂

    the receiver type doesn't match the enclosing class type

    根据其他答案,您不应该使用this作为参数(或将其声明为新变量),但错误消息说明了完全不同的情况

    事实上,您可以使用this作为参数,但只能在一个地方使用:作为a receiver parameter

    The receiver parameter is an optional syntactic device for an instance method or an inner class's constructor. For an instance method, the receiver parameter represents the object for which the method is invoked. For an inner class's constructor, the receiver parameter represents the immediately enclosing instance of the newly constructed object. In both cases, the receiver parameter exists solely to allow the type of the represented object to be denoted in source code, so that the type may be annotated (§9.7.4). The receiver parameter is not a formal parameter; more precisely, it is not a declaration of any kind of variable (§4.12.3), it is never bound to any value passed as an argument in a method invocation expression or class instance creation expression, and it has no effect whatsoever at run time.

    实际上,它看起来像

    class ThisDemo
    {
        void show(@Special ThisDemo this)
        {
            System.out.println(this);
        }
    }
    

    然后,您可以通过常规反射方式提取@Special注释

  3. # 3 楼答案

    是一个关键字,它引用方法或对象的当前实例。它用来指它所属的对象

    因此,将人体视为一个类。因为对象的实例可能会被称为不同的东西,比如John或Kyle,当在您将使用的方法中引用泛型人员时。例如,要获取任何人的心跳,都需要这样的东西。getHeartbeat()

    希望这能帮助你概念化这一点