简体   繁体   English

从另一个调用构造函数 - this 关键字的用法

[英]Calling a constructor from another - this keyword usage

Q. Identify the valid option which is used to invoke the no argument constructor, Product(), at Line 1.问:在第 1 行确定用于调用无参数构造函数 Product() 的有效选项。

class Product{
   int productId;
   String productName;

   Product( )   {
         productId=0; productName="";
  } 

   Product(int id, String name)   {
        //access Product() ---- Line 1
        productId=id;
        productName=name;
   } 
}

A. this();在他的();

Can you help me understand how 'this' reference variable can be used here?你能帮我理解如何在这里使用“这个”引用变量吗?

Can you help me understand how 'this' reference variable can be used here?你能帮我理解如何在这里使用“这个”引用变量吗?

this() isn't using a variable. this()没有使用变量。

It's a special syntactic construct which says "invoke another constructor in the same class".这是一个特殊的语法结构,表示“调用同一类中的另一个构造函数”。 It's called an "explicit constructor invocation" (or, more specifically, an " alternate constructor invocation "), and can only appear as the first statement in the constructor (see language spec ).它被称为“显式构造函数调用”(或更具体地说,“替代构造函数调用”),并且只能作为构造函数中的第一条语句出现(请参阅语言规范)。

However, you can use this as a "variable" later in the constructor, in order to access member variables or instance methods on the instance which is currently being constructed, for instance:但是,您可以使用this构造函数后的“变量”,以目前正在建设,例如在实例访问成员变量或实例方法:

this.productId = id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM