this关键字用于引用当前的类对象。它指示类,方法或构造函数的当前实例。它也可以用来调用当前的类方法或构造函数。它消除了类属性和参数名称相同之间的不确定性。如果我们声明类属性与参数名称相同,则这种情况将在程序中造成歧义,那么this关键字可以通过在类属性前添加前缀来消除歧义。可以将其作为参数传递给类方法或构造函数。
让我们了解以下有关this关键字如何工作的示例。
class Mobile { String modelname; int man_year; // 创建构造函数 Mobile(modelname, man_year){ modelname = modelname; man_year = 2020; print("Mobile's model name is: ${modelname}, and the manufacture year is: ${man_year}"); } } void main(){ Mobile mob = new Mobile("iPhone 11 ",2020); } }
输出
Mobile's model name is: iPhone 11 , and the manufacture year is: 2020
class Mobile { String modelname; int man_year; //Creating constructor Mobile(modelname, man_year){ this.modelname = modelname; this.man_year = 2020; print("Mobile's model name is: ${modelname}, and the manufacture year is: ${man_year}"); } } void main(){ Mobile mob = new Mobile("IPhone 11",2020);} }
输出
Mobile's model name is: IPhone 11, and the manufacture year is: 2020
上面的例子与前一个程序相同,但是this关键字的唯一差异。
this.modelname = modelname; this.man_year = 2020;
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
HarmonyOS快速入门与实战 -〔QCon+案例研习社〕